# Image Compressor – Compress JPG, PNG & WebP to Target KB (`gazidev/image-compressor`) Actor

Compress images in bulk without visible quality loss: optimised JPG, palette PNG, WebP or AVIF, or squeeze each file under a target size in KB. Strips metadata, keeps the original when it is already smaller, and reports savings per image. Bulk URLs or a dataset. $0.80 per 1,000.

- **URL**: https://apify.com/gazidev/image-compressor.md
- **Developed by:** [Cemal Atakli](https://apify.com/gazidev) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.80 / 1,000 image compresseds

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 – Compress JPG, PNG & WebP Images in Bulk (to a Target KB)

Compress hundreds or thousands of images from a list of URLs or an Apify dataset. Each file keeps its own format by default (JPG stays JPG, PNG stays PNG). The Actor picks the **lowest quality that still looks the same** (an SSIM check), can **squeeze every file under a target size in KB**, strips EXIF/GPS metadata, and **never returns a file that is larger than the original**. You get a download link and a savings report for every image.

**$0.80 per 1,000 compressed images.** Images that could not be made smaller are returned unchanged and are **free**.

### What it does

- **Visually lossless "auto" quality.** For JPG, WebP and AVIF it searches quality 60–90 and keeps the lowest setting whose SSIM stays at or above 0.98 (you can choose 0.95–0.995). SSIM is measured on a 512 px crop at full resolution, so artefacts are not hidden by downscaling.
- **Target file size.** Set `targetKb` (for example 100 for upload forms that require "under 100 KB"). Quality is lowered first, then PNGs switch to a palette, and as a last step the dimensions are reduced. Each row has `targetMet`.
- **Max width/height.** `maxDimension` downscales large photos (for example 2000 px for a web shop) before compression. It runs before the target size.
- **PNG palette compression (like TinyPNG).** In `auto` mode a PNG is reduced to 256 colours only when SSIM stays above the threshold, so logos, icons and screenshots shrink by 60–90% while photos and gradients stay full-colour.
- **Never larger.** With `keepOriginalIfSmaller` (on by default) an image that would not shrink by at least `minSavingsPercent` (2%) is returned unchanged and not charged.
- **Metadata stripped** (EXIF, GPS, camera data) for privacy and smaller files. The colour profile is kept, and EXIF orientation is applied to the pixels so phone photos are not sideways.
- **Savings report**: `originalKb`, `compressedKb`, `savedKb`, `savedPercent`, `quality`, `ssim` per image, plus a `SUMMARY` record with the run total.
- Optional format change: WebP, AVIF, JPG or PNG. HEIC/HEIF inputs become JPG.

### Use cases

- **Core Web Vitals / page speed**: compress every image of a site before upload and see how many KB you saved.
- **E-commerce catalogues**: shrink supplier product photos to a max size and a target KB before importing them into Shopify, WooCommerce or a PIM.
- **Scraper pipelines**: chain after an image scraper or our Image Downloader with `datasetId`, and store the compressed files in Apify storage.
- **Upload limits**: get every file under 100 KB, 200 KB or 1 MB for forms, marketplaces or email.

### Input example

```json
{
  "imageUrls": [
    "https://raw.githubusercontent.com/xinntao/Real-ESRGAN/master/inputs/children-alpha.png",
    "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/gps/DSCN0010.jpg"
  ],
  "outputFormat": "same",
  "quality": "auto",
  "targetKb": 0,
  "maxDimension": 0
}
```

Other sources: `bulkText` (one URL per line or a CSV with a `url` column), `sourceFileUrl` (a public .txt/.csv, e.g. a Google Sheet published as CSV) and `datasetId` + `datasetField` (any Apify dataset you can read).

### Output example

```json
{
  "sourceUrl": "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/gps/DSCN0010.jpg",
  "status": "compressed",
  "imageUrl": "https://api.apify.com/v2/key-value-stores/<storeId>/records/00002-DSCN0010-1a2b3c.jpg",
  "format": "jpg",
  "width": 640,
  "height": 480,
  "originalKb": 161.7,
  "compressedKb": 123.2,
  "savedKb": 38.5,
  "savedPercent": 23.8,
  "quality": 79,
  "ssim": 0.9803,
  "keptOriginal": false,
  "metadataStripped": true
}
```

`status` is `compressed` (charged), `kept-original` (free; the unchanged file is still stored), `not-smaller` (free; only when you turn `keepOriginalIfSmaller` off) or `error` (free, with `errorCode`). The `SUMMARY` record in the key-value store has `images`, `compressed`, `keptOriginal`, `failed`, `totalOriginalKb`, `totalCompressedKb`, `totalSavedKb`, `overallSavedPercent` and `avgSavedPercent`. 1 KB = 1,000 bytes.

### Pricing

| Event | Price |
|---|---|
| Image compressed (output smaller than the original) | $0.0008 ($0.80 per 1,000) |
| Actor start | $0.00005 |

Free: images kept unchanged, failed downloads, non-images, invalid URLs and duplicates. If you set a maximum total charge, the run stops cleanly when it is reached and `SUMMARY.stoppedAtMaxCharge` is `true`.

| Actor (Apify Store, Nov 2026) | Price per image |
|---|---|
| **This Actor** | **$0.0008**, unchanged files free |
| marielise.dev/image-converter | $0.002 (files ≤ 500 KB) |
| conserving_celerytop/image-converter-compressor | $0.003 |
| ntriqpro/image-batch-optimizer | $0.01 |

### Limits (honest)

- Inputs must be public direct image links. Pages that block datacenter IPs may need the optional proxy.
- Animated GIF, WebP and PNG files are returned unchanged (free); only static images are recompressed.
- SSIM is a good but not perfect measure of "looks the same". It is checked on the central 512 × 512 px area. Use 0.99 for very safe results or 0.95 for smaller files.
- Files that were already compressed well (for example by TinyPNG or a CDN) often cannot shrink further; they are returned unchanged for free.
- A strict `targetKb` takes priority over quality: very small targets give visible artefacts or smaller dimensions (`resized: true`, `ssim` empty).
- No AI upscaling, background removal or format-specific tricks such as JPEG XL or MozJPEG.

### FAQ

**Does it change the format?** Not by default. Choose WebP or AVIF in `outputFormat` for the smallest files; for a full converter with resize modes see our Bulk Image Converter.

**Is it lossless?** PNG output without a palette is lossless. JPG, WebP and AVIF are lossy but tuned to stay visually identical (SSIM ≥ 0.98 by default).

**Where are the files?** In the run's key-value store. `imageUrl` is a direct download link; the Storage tab lists all files.

**Why was I not charged for some images?** They could not be made at least 2% smaller, so the original was returned. You only pay for real savings.

### Use with AI agents (Apify MCP)

Add this Actor to an MCP client through the Apify MCP server (`https://mcp.apify.com`, tool `gazidev/image-compressor`). An agent can pass a list of image URLs with `targetKb` or `maxDimension` and read `imageUrl`, `savedPercent` and the `SUMMARY` record from the result.

# Actor input Schema

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

Direct links to JPG, PNG, WebP, AVIF, HEIC/HEIF, TIFF, GIF or BMP files. Duplicates are removed; invalid values and failed downloads are reported for free.

## `bulkText` (type: `string`):

One URL per line, or a CSV with a `url` / `image` column.

## `sourceFileUrl` (type: `string`):

Public .txt or .csv link (Google Sheets 'Publish to web → CSV' works).

## `datasetId` (type: `string`):

Chain after a scraper (e.g. product images) or our Image Downloader.

## `datasetField` (type: `string`):

Arrays of URLs are accepted too.

## `outputFormat` (type: `string`):

'Same as input' keeps each file's format. HEIC/HEIF become JPG and BMP becomes PNG. Animated GIF/WebP/PNG files are returned unchanged (free).

## `quality` (type: `string`):

`auto` (default): for JPG, WebP and AVIF finds the lowest quality between 60 and 90 that keeps SSIM at or above the threshold below (measured on a native-resolution 512 px crop). Or a fixed number 1–100.

## `minSsim` (type: `string`):

Used by `auto` quality and by the automatic palette PNG decision.

## `targetKb` (type: `integer`):

Squeeze each file under this size (1 KB = 1,000 bytes). Lowers quality first (JPG, WebP, AVIF) or switches PNG to a palette, then shrinks the dimensions step by step. Overrides the quality threshold. 0 = off.

## `maxDimension` (type: `integer`):

Downscale images whose longest side is larger than this before compressing (aspect ratio kept, never enlarged). Runs before the target size. 0 = off.

## `pngPalette` (type: `string`):

Palette PNGs are often 60–80% smaller. Auto keeps full colour for photos and gradients where the palette would show banding.

## `keepOriginalIfSmaller` (type: `boolean`):

On (default): the result is never larger than the original. Those images are returned unchanged and are not charged.

## `minSavingsPercent` (type: `integer`):

With 'Keep the original' on, an image that shrinks by less than this is returned unchanged and not charged. 0 = keep any saving.

## `keepMetadata` (type: `boolean`):

Off (default) strips EXIF, GPS location and camera data for privacy and smaller files; the colour profile is kept. Orientation is always applied to the pixels.

## `backgroundColor` (type: `string`):

Used when a transparent image is saved as JPG.

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

0 = no limit.

## `maxFileSizeMb` (type: `integer`):

Larger files are skipped for free.

## `maxConcurrency` (type: `integer`):

Lower it for slow or rate-limited hosts.

## `proxyConfiguration` (type: `object`):

Only needed if an image host blocks datacenter IPs.

## Actor input object example

```json
{
  "imageUrls": [
    "https://raw.githubusercontent.com/xinntao/Real-ESRGAN/master/inputs/children-alpha.png",
    "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/gps/DSCN0010.jpg"
  ],
  "datasetField": "url",
  "outputFormat": "same",
  "quality": "auto",
  "minSsim": "0.98",
  "targetKb": 0,
  "maxDimension": 0,
  "pngPalette": "auto",
  "keepOriginalIfSmaller": true,
  "minSavingsPercent": 2,
  "keepMetadata": false,
  "backgroundColor": "#ffffff",
  "maxImages": 0,
  "maxFileSizeMb": 50,
  "maxConcurrency": 6
}
```

# Actor output Schema

## `overview` (type: `string`):

No description

## `results` (type: `string`):

No description

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

No description

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

No description

# 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://raw.githubusercontent.com/xinntao/Real-ESRGAN/master/inputs/children-alpha.png",
        "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/gps/DSCN0010.jpg"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("gazidev/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://raw.githubusercontent.com/xinntao/Real-ESRGAN/master/inputs/children-alpha.png",
        "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/gps/DSCN0010.jpg",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("gazidev/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://raw.githubusercontent.com/xinntao/Real-ESRGAN/master/inputs/children-alpha.png",
    "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/gps/DSCN0010.jpg"
  ]
}' |
apify call gazidev/image-compressor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,gazidev/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/RylEa7EzrYWlDswoD/builds/GG9YnWu2W1vLdns98/openapi.json
