# Image Converter & Compressor: WebP, AVIF, HEIC, JPG, PNG (`stas_k/image-converter`) Actor

Most image converters bill every file they touch, even files they cannot decode. This one charges only for a converted image you can download: the signature decides what an image is, a broken or non image file comes back free with a reason, and converted files land in the run store plus a zip.

- **URL**: https://apify.com/stas_k/image-converter.md
- **Developed by:** [Stas K](https://apify.com/stas_k) (community)
- **Categories:** Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

$2.00 / 1,000 converted images

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Image Converter & Compressor: WebP, AVIF, HEIC, JPG, PNG

Converts images from urls into WebP, JPEG, PNG or AVIF, resizes them without upscaling,
strips metadata on request and hands back every delivered file both on its own row and
in one zip. The buyer pays per converted image that really exists in the run store.

Most image converters in this store bill every file they touch, including files they
could not decode, and return nothing when a batch is cut. Here the signature decides
what an image is: an html page, a pdf, a video, a truncated file or a file over the
pixel ceiling comes back as its own row with `billable: false` and a plain reason.

### What comes out

- One dataset row per input line. A delivered image has `status: OK`, the delivered
  size, the original size, `bytesIn`, `bytesOut`, `savedPercent` and `outputKey`.
- The converted file itself in the run key-value store under `images_<index>-<name>.<ext>` (a record key allows only letters, digits and !-\_.'() , so the prefix is flat, not a folder).
- One archive `converted-images.zip` with the same files, linked from the run's
  output card.

### Input

| field | default | meaning |
|---|---|---|
| `imageUrls` | - | http(s) urls, one per line. Read once each: a repeat, a bad url and a line past `maxImages` are free rows with a reason. |
| `format` | `webp` | `webp`, `jpeg`, `png` or `avif`. |
| `quality` | `82` | 1 to 100 for JPEG, WebP and AVIF. PNG ignores it. |
| `maxWidth`, `maxHeight` | `2000` | Scale down to fit, keep the aspect ratio, never upscale. `0` means no limit. |
| `stripMetadata` | `true` | Drops EXIF, GPS and camera tags. The orientation itself is applied to the pixels first, so a phone photo stays upright. |
| `background` | `#FFFFFF` | The colour transparency is flattened onto for JPEG. |
| `maxImages` | `20` | The list is cut here, the rest is free with `NOT_CHECKED_LIMIT`. |

### Price

$2.00 per 1,000 converted images (`image-converted`, $0.002 per image). The platform
adds its own start event. Nothing else is charged: a page of html, a broken file, a
private address, a timeout, a file over 25 MB, an image over 40 megapixels, a file that
could not be stored and every row of a stopped run are free.

`billable` on a row is the claim from the price list; the money actually taken is
`chargedEvents` in the run summary. When the two differ, the summary is right.

### Statuses

`OK` means the file is delivered and can be downloaded. Everything else is free:

- `NOT_CHECKED_INVALID` - the line is not an http(s) url.
- `NOT_CHECKED_DUPLICATE` - the same url came earlier.
- `NOT_CHECKED_LIMIT` - past `maxImages`.
- `NOT_CHECKED_PRIVATE_ADDRESS` - a host name answered with a non public address,
  whether the image host or any hop of the redirect chain.
- `NOT_CHECKED_DNS_ERROR` - the host name does not resolve or is not a valid name.
- `NOT_CHECKED_FETCH_ERROR` - HTTP error or timeout.
- `NOT_CHECKED_TOO_LARGE` - more than 25 MB.
- `NOT_CHECKED_NOT_AN_IMAGE` - the bytes are not an image, whatever the url says.
- `NOT_CHECKED_DECODE_ERROR` - an image signature, but the file cannot be read.
- `NOT_CHECKED_TOO_MANY_PIXELS` - more than 40 megapixels: the cap that fits next
  to the image peak inside 1 GB of memory, it is not the bytes on disk.
- `NOT_CHECKED_UNSUPPORTED_TARGET` - the image has no encoder for the asked format.
- `NOT_CHECKED_STORE_ERROR` - the converted file could not be written to the store, so
  there is nothing to download and nothing to charge.
- `NOT_CHECKED_CAP` - the spending cap was reached: this file and everything after it
  are free, the file itself is already in the store under its `outputKey`.
- `NOT_CHECKED_TIME`, `NOT_CHECKED_BILLING`, `NOT_CHECKED_ERROR` - the run stopped
  before this image; `stopReason` in the summary says why.

### Measured

One CPU, this project's machine, a 4000x3000 photo delivered as a 1 056 224 byte JPEG:

| target | time | size | note |
|---|---|---|---|
| webp, 2000 px | 0.69 s | 102 800 | 10x smaller |
| jpeg, 2000 px | 0.22 s | 187 071 | |
| png, 2000 px | 0.52 s | 2 903 277 | 2.7x bigger, `savedPercent` says so |
| avif, 2000 px | 0.25 s | 156 027 | |

The wall clock numbers are from a 4000x3000 source; smaller images are faster. PNG of a
photo usually grows, and the row reports a negative `savedPercent` instead of pretending
otherwise.

### What this actor does not do

- It does not upscale, crop, rotate by hand or change the aspect ratio.
- It does not convert to gif, bmp or tiff.
- It does not keep an ICC profile when `stripMetadata` is on, so an unusual colour
  profile can shift colours.
- It does not convert animated gif or animated webp frame by frame: the first frame is
  used.
- It does not fetch a page to find the image inside it: the url must point at the image.
- It does not write into the buyer's own store: files go into the store of this run,
  which the buyer owns.

### Local run

```bash
python -m src.main
```

with `APIFY_LOCAL_STORAGE_DIR=./storage` and an `INPUT.json` in
`storage/key_value_stores/default/`.

# Actor input Schema

## `imageUrls` (type: `array`):

One http(s) url per line. Each url is read once: a repeat, a line that is not a url and a line beyond maxImages come back as their own free row with the reason. The file signature decides whether the bytes are an image, never the file name or the content type.

## `format` (type: `string`):

The format every delivered image is written in. WebP is the safe default for the web: it keeps transparency and is far smaller than JPEG at the same quality. PNG is for lossless work, JPEG for the widest compatibility, AVIF for the smallest files at the cost of encoding time.

## `quality` (type: `integer`):

Encoder quality for JPEG, WebP and AVIF. 82 is the point where a photo stops looking different at half the size; below 60 artefacts show on gradients, above 90 the files grow fast for very little gain. PNG ignores it.

## `maxWidth` (type: `integer`):

A wider image is scaled down to this width and never upscaled. Aspect ratio is kept, so the height follows the width. 0 means no width limit.

## `maxHeight` (type: `integer`):

The same limit for the height. An image that fits both limits is left at its own size. 0 means no height limit.

## `stripMetadata` (type: `boolean`):

Drops EXIF, GPS, camera and software tags from the converted file. The orientation itself is applied to the pixels first, so a phone photo stays upright. Turn it off only when the metadata is the point.

## `background` (type: `string`):

The colour an image with transparency is flattened onto when the target format has no alpha channel, which is JPEG. A hex colour like #FFFFFF or #000000.

## `maxImages` (type: `integer`):

The list is cut here and the rest comes back free with status NOT_CHECKED_LIMIT. 0 means the default of 20, and the summary reports the number actually applied.

## Actor input object example

```json
{
  "imageUrls": [
    "https://www.w3.org/Icons/w3c_home.png",
    "https://www.w3.org/Icons/valid-html401.png"
  ],
  "format": "webp",
  "quality": 82,
  "maxWidth": 2000,
  "maxHeight": 2000,
  "stripMetadata": true,
  "background": "#FFFFFF",
  "maxImages": 20
}
```

# Actor output Schema

## `dataset` (type: `string`):

One row per image. status is OK when the row carries a converted file, or NOT_CHECKED\_\* with the reason in plain words: INVALID (the line is not an http url), DUPLICATE (the same url came earlier), LIMIT (past maxImages), PRIVATE_ADDRESS (a host name really answered with a non public address, whether the image host or a redirect hop), DNS_ERROR (the host name does not resolve or is not a valid name), FETCH_ERROR (the file could not be downloaded), TOO_LARGE (bigger than 25 MB), NOT_AN_IMAGE (the bytes are not an image, whatever the url says), DECODE_ERROR (the signature is right but the file cannot be read), TOO_MANY_PIXELS (more than 60 megapixels), UNSUPPORTED_TARGET (the image has no encoder for the asked format), STORE_ERROR (the converted file could not be written to the key-value store), TIME, CAP, BILLING and ERROR (the run stopped before this image for the reason in the summary). sourceFormat is what the file really was, width and height are the delivered size, widthIn and heightIn the original one, bytesIn and bytesOut the sizes before and after, savedPercent their difference (it can be negative), and outputKey is where the delivered file lives in this run key-value store. billable is true only on a row that carries a converted file; the money actually taken is in the run summary.

## `files` (type: `string`):

Every delivered image in one archive, under the same names as the outputKey fields in the dataset. An image that was refused for any reason is not in the archive and was not charged.

## `summary` (type: `string`):

Run summary. requested is how many lines were sent, uniqueImages is how many different urls were read, linesThatAreNotImages counts the lines that never were an image request (a bad url, a repeat, a blank line, a line past maxImages) and imagesAttempted is the rest, the lines that really were images. processedImages counts an image that was decoded, even when the conversion failed, and notCheckedImages counts an image this run never reached, so processedImages plus notCheckedImages always equals imagesAttempted and imagesAttempted plus linesThatAreNotImages always equals requested. deliveredImages is how many converted files were written and chargedEvents is how much money was really taken, which is the number to trust when the two differ. bytesInTotal and bytesOutTotal are the sizes before and after, savedBytesTotal their difference. zipKey, zipBytes and imagesInZip describe the archive, and zipError names a failure to build it without touching the delivered files themselves. billingActive and billingReason say whether this run could charge at all; a run with billing off still delivers files and reports chargedEvents 0. stopReason names the reason the run stopped early, if it did, and deliveredUncharged counts files that are in the store without money taken. datasetItemCount is what this run wrote, datasetItemCountApi is what the platform reports and it lags by minutes, so a smaller number there is a lag and not a lost row. The same summary is in the summary store under RUN_SUMMARY-<runId>.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "imageUrls": [
        "https://www.w3.org/Icons/w3c_home.png",
        "https://www.w3.org/Icons/valid-html401.png"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("stas_k/image-converter").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "imageUrls": [
        "https://www.w3.org/Icons/w3c_home.png",
        "https://www.w3.org/Icons/valid-html401.png",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("stas_k/image-converter").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "imageUrls": [
    "https://www.w3.org/Icons/w3c_home.png",
    "https://www.w3.org/Icons/valid-html401.png"
  ]
}' |
apify call stas_k/image-converter --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,stas_k/image-converter"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Y3H9Re4xk1dH2gBtj/builds/fpA2vLIUrfsTxofxs/openapi.json
