# Image Compressor API - Batch JPG, PNG, WebP to Target Size (`stas_k/image-compressor`) Actor

Most image compressors bill every image they touch, even when the file did not get smaller. This one charges only when the delivered image really shrank: if nothing was saved you get the original back free, with the reason on the row.

- **URL**: https://apify.com/stas_k/image-compressor.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

$4.00 / 1,000 compressed 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 Compressor API - Batch JPG, PNG, WebP to Target Size

Most compressors bill every image they touch, including the ones they could not make
smaller. This actor has one rule on top of the park rule: **you pay for an image that
really got smaller**. When the re-encode is not smaller than the input, the original
bytes are delivered untouched, the row says `compressed: false`, and it costs nothing.

Everything happens inside the container with Pillow: no key, no image service, no
per image cost besides the platform itself.

### What you send

`imageUrls` is a list of http(s) links, one per line. Two optional numbers decide the
work:

- `targetKB` asks for a weight: the encoder lowers quality until the file fits, and
  only then scales the picture down, because a sharp photo beats a blurry one.
- `quality` is the ceiling of that search, and the quality used when no target is set.
- `format` is `keep` by default: the bytes decide the format, so a png is not quietly
  turned into a jpeg. Naming webp, jpeg, png or avif asks for a conversion.
- `maxWidth` / `maxHeight` are 0 by default. This actor sells weight, not dimensions:
  it does not resize unless you ask.

### What you get

One dataset row per image with the delivered size, the size it came from, bytes saved,
percent saved, the quality the search landed on, whether the target was reached, and
`outputKey` pointing at the file in the run store. Every delivered image is also packed
into one zip, `compressed-images.zip`.

### What is free

A row that is not a delivered file costs nothing and names its reason: a line that is
not an http url, a repeat, a line past `maxImages`, a private or unresolvable host, a
file that cannot be downloaded, a file over 25 MB, bytes that are not an image by their
own signature, a file whose signature is right but which cannot be decoded, an image
over 40 megapixels, and every row for work the run never reached because it stopped early
(`TIME`, `CAP`, `BILLING`, `ERROR`).

And the rule this actor exists for: **an image that did not get smaller is delivered
unchanged and is free**.

### Money

The event is `image-compressed`, charged per delivered image that really shrank. One SDK
call writes the row and takes the money together, so a row you can read is a row that
was written. The spending cap is checked before each image; on the cap the run stops,
the rest of the images come back free with `NOT_CHECKED_CAP`, and the summary says
`stopReason: spending-cap`. If the price cannot be read at all, the run stops before the
first paid image and nothing is delivered - a price this actor cannot see is a price it
does not guess.

`chargedEvents` in the summary is the number to trust. The platform reports
`chargedEventCounts` with a lag, so a zero in the first minute is not proof that nothing
was charged.

### Honest limits

- 25 MB per input file and 40 megapixels per image. Both are measured limits of the
  container memory, not taste: a 40 MP RGBA image already takes about 600 MB of the
  1024 MB.
- No resize unless `maxWidth` or `maxHeight` is set.
- PNG is lossless, so `quality` and `targetKB` only get what deflate can give; a png
  that cannot be made smaller comes back unchanged and free.
- A source format this actor cannot write back (gif, heic, tiff, bmp) is delivered as
  jpeg, and the row names the source format it came from.
- Redirect hops are resolved and refused before their request goes out, so a public link
  that answers 302 into a private network never reaches it.
- The archive is built after the last image; if it fails, every file is still in the
  store under its `outputKey` and the summary says why.
- Nothing here reads a key or calls a third party, so there is no quota to hit and no
  external outage to wait out.

# 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.

## `targetKB` (type: `integer`):

The weight every delivered image should fit under. The encoder lowers quality until the file fits, and only then scales the picture down, because a sharp photo beats a blurry one. 0 means no target: the image is re-encoded at your quality and nothing else. The row says whether the target was reached, and an image that cannot be squeezed under it is delivered at the smallest size found, priced the same.

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

Encoder quality for JPEG, WebP and AVIF, and the ceiling of the search when targetKB is set: the search never goes above this number. 80 is the point where a photo stops looking different at half the size; below 60 artefacts show on gradients. PNG is lossless and ignores it.

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

Keep means the format stays the one the bytes already have, so a compressor does not quietly convert your png into a jpeg. A source format this actor cannot write back (gif, heic, tiff, bmp) is delivered as jpeg, and the row names the source format it came from. Naming a format asks for a conversion.

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

A wider image is scaled down to this width and never upscaled. 0 keeps every pixel: this actor sells weight, not dimensions, and it does not resize unless you ask.

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

The same limit for the height. 0 keeps every pixel.

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

Drops EXIF, GPS, camera and software tags from the delivered file, which is usually a few kilobytes of the weight and all of the privacy. 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 delivered 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://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg",
    "https://upload.wikimedia.org/wikipedia/commons/6/6e/Golde33443.jpg"
  ],
  "targetKB": 0,
  "quality": 80,
  "format": "keep",
  "maxWidth": 0,
  "maxHeight": 0,
  "stripMetadata": true,
  "background": "#FFFFFF",
  "maxImages": 20
}
```

# Actor output Schema

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

One row per image. status is OK when the row carries a downloadable 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 40 megapixels), UNSUPPORTED_TARGET (the image has no encoder for the asked format), STORE_ERROR (the 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). compressed is true when the delivered file is really smaller than the input; when it is false the original bytes are delivered untouched, savedBytes is 0 and the row costs nothing. bytesIn and bytesOut are the sizes before and after delivery, savedPercent their difference, targetKB the weight you asked for, targetReached whether the delivered file fits it, qualityUsed the encoder quality the search landed on and resized whether the pixels were scaled down. width and height are the delivered size, widthIn and heightIn the original one, sourceFormat what the file really was, formatNote says when a format you named could not be honoured, and outputKey is where the file lives in this run key-value store. billable is true only on a row that carries a file this actor really shrank; 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. processedImages counts an image that was decoded, even when compressing it 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 files were written, compressedImages how many of them really got smaller and alreadySmallImages how many came back unchanged and free; targetMissed counts images that could not be squeezed under targetKB. chargedEvents is how much money was really taken, which is the number to trust when it differs from deliveredImages. bytesInTotal and bytesOutTotal are the sizes before and after, savedBytesTotal and savedPercentTotal 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, and deliveredUncharged counts files 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://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg",
        "https://upload.wikimedia.org/wikipedia/commons/6/6e/Golde33443.jpg"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("stas_k/image-compressor").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://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg",
        "https://upload.wikimedia.org/wikipedia/commons/6/6e/Golde33443.jpg",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("stas_k/image-compressor").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://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg",
    "https://upload.wikimedia.org/wikipedia/commons/6/6e/Golde33443.jpg"
  ]
}' |
apify call stas_k/image-compressor --silent --output-dataset

```

## MCP server setup

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

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/ym91n7X4hqvkEwwkz/builds/hfCGeUyhpnkaFj6mV/openapi.json
