# Batch Image Compress & Convert — WebP/JPEG/PNG (`ingenious_quip_bxq/batch-image-compress`) Actor

Batch WebP/JPEG/PNG optimization for image URL lists (or downloader dataset/KV). KV + bytesBefore/After, savedPct, EXIF strip. Failed free. AVIF: 「runtime optional / currently unavailable on this runtime」— not a selling point. No crawl.

- **URL**: https://apify.com/ingenious\_quip\_bxq/batch-image-compress.md
- **Developed by:** [新世紀書僮](https://apify.com/ingenious_quip_bxq) (community)
- **Categories:** Developer tools, AI, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 image converteds

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

## Batch Image Compress & Convert — WebP/JPEG/PNG

**Batch WebP / JPEG / PNG optimization pipeline for image URL lists (or `batch-image-downloader` dataset/KV fields) with before/after sizes.**

Give this Actor direct image URLs — or point it at an upstream Apify dataset / KV store from **batch-image-downloader**. It downloads (or reads KV bytes), re-encodes with Pillow to **WebP, JPEG, or PNG**, optionally strips EXIF/GPS, stores the result in KV, and writes a dataset row with `bytesBefore` / `bytesAfter` / `savedPct`, dims, format, and sha256. Failed, non-image, and oversized inputs are free by default.

**Positioning:** batch optimization pipeline for page-speed / CMS / Core Web Vitals — **not** site crawling or image scraping. Differentiates from **batch-image-downloader** (no page crawl, no `<img>` extraction).

**AVIF:** runtime optional / currently unavailable on this runtime — not a selling point. Prefer WebP/JPEG/PNG.

### What you get

- Batch **compress / convert** of image URL lists → KV (`opt-<sha256>.<ext>`)
- Compatible with **batch-image-downloader** output (`sourceUrl`, `kvKey`, optional `sourceDatasetId` / `sourceKvStoreId`)
- Formats: **WebP / JPEG / PNG** (primary). AVIF is runtime optional / currently unavailable on this runtime
- Metadata: content type, bytes before/after, savedPct, width/height, sha256, format
- Optional **EXIF / GPS strip**; optional cheaper **strip-only** mode (no pixel re-encode)
- Default **512 MB** memory (target 256–512); failed / non-image / oversized free unless you opt in
- **No page crawl, no `<img>` extraction** — pass image URLs or an upstream media dataset

### Measured results

Cloud benches on build **0.1.1**, **512 MB** (Asia/Taipei 2026-10-02):

| Run | Input | Stored | Peak RSS | Platform cost |
|---|---|---|---|---|
| smoke | 3 URLs (2 ok / 1×404 free) → WebP | 2 | 89 MB | ~$0.00039 |
| bench | 12 URLs (10 ok / 2 err free) → WebP | 10 | 92 MB | ~$0.00087 (~$0.000087 / image) |
| strip-only | 2 URLs metadata strip | 2 | ~90 MB | ~$0.00038 |

Bench avg savedPct ≈ **32%** (WebP q80). See **Measured results** above for measured platform cost.

### Use cases

- Optimize a product-image URL list for Core Web Vitals before CMS upload
- Chain after **batch-image-downloader**: download → compress into WebP/JPEG/PNG with EXIF stripped
- Privacy pass: strip GPS/EXIF from owned asset packs without changing pixels (`stripOnly`)

### How to use

```json
{
  "imageUrls": [
    { "url": "https://www.w3.org/Icons/w3c_home.png" },
    { "url": "https://httpbin.org/image/jpeg" }
  ],
  "targetFormat": "webp",
  "quality": 80,
  "stripExif": true,
  "maxImages": 50,
  "maxConcurrency": 4
}
```

Chain from batch-image-downloader:

```json
{
  "sourceDatasetId": "<dataset-id-from-downloader-run>",
  "sourceKvStoreId": "<kv-store-id-from-downloader-run>",
  "imageUrlField": "sourceUrl",
  "kvKeyField": "kvKey",
  "targetFormat": "webp",
  "quality": 80,
  "stripExif": true
}
```

Example success row:

```json
{
  "sourceUrl": "https://httpbin.org/image/jpeg",
  "status": "success",
  "format": "webp",
  "contentType": "image/webp",
  "bytesBefore": 35588,
  "bytesAfter": 12400,
  "savedPct": 65.16,
  "width": 239,
  "height": 178,
  "sha256": "…",
  "kvKey": "opt-<sha256>.webp",
  "strippedExif": true,
  "durationMs": 45
}
```

### Pricing (pay-per-event)

| Event | Price | When |
|---|---|---|
| Actor start | **$0.001** / GB (1 GB min) | Once per run |
| Image converted (primary) | **$0.002** | Each successful compress/convert KV store |
| Image strip-only | **$0.001** | When `stripOnly` succeeds (metadata only) |
| Failed / non-image / oversized / duplicate | **$0** | Default (`chargeFailedImages=false`) |

Example: 1,000 successful converts ≈ **$2.00** + start (before platform CU/storage). Failed items are never charged by default.

### Integrations

```python
from apify_client import ApifyClient
client = ApifyClient("<YOUR_TOKEN>")
run = client.actor("YOUR_USERNAME/batch-image-compress").call(run_input={
    "imageUrls": [
        {"url": "https://www.w3.org/Icons/w3c_home.png"},
        {"url": "https://httpbin.org/image/jpeg"},
    ],
    "targetFormat": "webp",
    "quality": 80,
    "stripExif": True,
    "maxImages": 50,
})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item.get("sourceUrl"), item.get("status"), item.get("savedPct"), item.get("kvKey"))
```

### Related Actors

- [Batch Image Downloader](https://apify.com/YOUR_USERNAME/batch-image-downloader) — download image URLs or extract page imgs into KV (this Actor does not crawl)
- [Sitemap URL Extractor](https://apify.com/YOUR_USERNAME/sitemap-url-discovery) — discover image/PDF URLs from sitemaps
- [Bulk URL Status Checker](https://apify.com/YOUR_USERNAME/url-status-checker) — filter live URLs before optimize

### Known limits

- Does **not** crawl HTML pages or extract `<img>` / `og:image` — use **batch-image-downloader** for that
- AVIF is runtime optional / currently unavailable on this runtime — pick WebP/JPEG/PNG
- Animated GIF / multi-frame: first-frame / static re-encode behavior via Pillow
- Copyright / robots: you are responsible for lawful use of source assets you optimize
- Not a “scrape any website’s images” tool — designed for owned or permitted URL lists and optimization pipelines

### License

AGPL-3.0 (see `LICENSE`). Runtime stack: `httpx` (BSD), `Pillow` (MIT-CMU), Apify SDK.

# Changelog

This Actor's version history is a separate document: https://apify.com/ingenious\_quip\_bxq/batch-image-compress/changelog.md

# Actor input Schema

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

Direct image URLs to download and compress. Accepts strings, {"url": "..."}, or requestListSources-style entries. Deduplicated, order preserved. No page crawl — pass image URLs only.

## `sourceDatasetId` (type: `string`):

Optional Apify dataset ID (e.g. from batch-image-downloader). Reads image URLs from each item via imageUrlField (default sourceUrl, then url). If sourceKvStoreId is also set and items have kvKey, prefers KV bytes over re-download.

## `sourceKvStoreId` (type: `string`):

Optional key-value store ID holding already-downloaded images. Used with sourceDatasetId rows that include kvKey, or with kvKeyPrefix to list matching keys.

## `imageUrlField` (type: `string`):

Field name on sourceDatasetId items that holds the image URL. Default sourceUrl (batch-image-downloader). Falls back to url / imageUrl.

## `kvKeyField` (type: `string`):

Field on sourceDatasetId items naming the binary in sourceKvStoreId. Default kvKey.

## `targetFormat` (type: `string`):

Output image format. avif is used when the runtime supports it; otherwise the run marks those rows as error (free) unless you choose another format. keep = same family as source (jpeg/png/webp) with re-encode.

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

Quality 1–95 for WebP / JPEG / AVIF (ignored for PNG).

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

If > 0, downscale so width ≤ this (keeps aspect ratio). 0 = no resize.

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

If > 0, downscale so height ≤ this (keeps aspect ratio). 0 = no resize.

## `stripExif` (type: `boolean`):

Remove EXIF and GPS metadata from the output (privacy). On by default for convert mode.

## `stripOnly` (type: `boolean`):

When on, only strip metadata and re-save in the source format (cheaper image-strip-only event). Ignores targetFormat / quality / resize.

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

Stop after processing this many unique images (0 = no limit). Caps cost.

## `maxBytesPerImage` (type: `integer`):

Skip (free) sources larger than this many bytes. Default 15 MB.

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

Parallel downloads / converts. Keep moderate to stay within 256–512 MB.

## `requestTimeoutSecs` (type: `integer`):

Timeout per HTTP download.

## `maxRetries` (type: `integer`):

Retries for transient network / 5xx failures.

## `minDelayMsPerHost` (type: `integer`):

Minimum milliseconds between starting downloads to the same host. 0 = no extra delay.

## `userAgent` (type: `string`):

HTTP User-Agent for image downloads.

## `skipDuplicatesByHash` (type: `boolean`):

If on, identical output bytes after the first success are recorded as status=duplicate (free) and not re-stored.

## `kvKeyPrefix` (type: `string`):

Prefix for stored file keys, e.g. opt- → opt-<sha256>.<ext>. Only a-zA-Z0-9!-\_.'() allowed (no slashes).

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

Optional Apify Proxy. Off by default — use only when sources require it.

## `chargeFailedImages` (type: `boolean`):

When off (default), only successful KV stores are charged. Failed/non-image/oversized/duplicate rows are saved free.

## Actor input object example

```json
{
  "imageUrls": [
    {
      "url": "https://www.w3.org/Icons/w3c_home.png"
    },
    {
      "url": "https://httpbin.org/image/jpeg"
    },
    {
      "url": "https://httpbin.org/image/png"
    }
  ],
  "imageUrlField": "sourceUrl",
  "kvKeyField": "kvKey",
  "targetFormat": "webp",
  "quality": 80,
  "maxWidth": 0,
  "maxHeight": 0,
  "stripExif": true,
  "stripOnly": false,
  "maxImages": 50,
  "maxBytesPerImage": 15728640,
  "maxConcurrency": 4,
  "requestTimeoutSecs": 30,
  "maxRetries": 2,
  "minDelayMsPerHost": 50,
  "userAgent": "Mozilla/5.0 (compatible; BatchImageCompress/0.1; +https://apify.com)",
  "skipDuplicatesByHash": true,
  "kvKeyPrefix": "opt-",
  "chargeFailedImages": false
}
```

# Actor output Schema

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

Default dataset items: sourceUrl, status, format, contentType, bytesBefore, bytesAfter, savedPct, width, height, sha256, kvKey, strippedExif, errors, durationMs. Views: overview.

## `images` (type: `string`):

Binary image records under the configured kvKeyPrefix (default opt-).

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

Key-value store record SUMMARY (JSON): counts, charged, durationSecs, peakMemoryMb, avifSupported.

## `output` (type: `string`):

Key-value store record OUTPUT (JSON): same run summary as SUMMARY plus charged event counts.

# 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": [
        {
            "url": "https://www.w3.org/Icons/w3c_home.png"
        },
        {
            "url": "https://httpbin.org/image/jpeg"
        },
        {
            "url": "https://httpbin.org/image/png"
        }
    ],
    "targetFormat": "webp",
    "quality": 80,
    "stripExif": true,
    "stripOnly": false,
    "maxImages": 50,
    "skipDuplicatesByHash": true,
    "chargeFailedImages": false
};

// Run the Actor and wait for it to finish
const run = await client.actor("ingenious_quip_bxq/batch-image-compress").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": [
        { "url": "https://www.w3.org/Icons/w3c_home.png" },
        { "url": "https://httpbin.org/image/jpeg" },
        { "url": "https://httpbin.org/image/png" },
    ],
    "targetFormat": "webp",
    "quality": 80,
    "stripExif": True,
    "stripOnly": False,
    "maxImages": 50,
    "skipDuplicatesByHash": True,
    "chargeFailedImages": False,
}

# Run the Actor and wait for it to finish
run = client.actor("ingenious_quip_bxq/batch-image-compress").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": [
    {
      "url": "https://www.w3.org/Icons/w3c_home.png"
    },
    {
      "url": "https://httpbin.org/image/jpeg"
    },
    {
      "url": "https://httpbin.org/image/png"
    }
  ],
  "targetFormat": "webp",
  "quality": 80,
  "stripExif": true,
  "stripOnly": false,
  "maxImages": 50,
  "skipDuplicatesByHash": true,
  "chargeFailedImages": false
}' |
apify call ingenious_quip_bxq/batch-image-compress --silent --output-dataset

```

## MCP server setup

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

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/N6894XhpYrbZYCzO0/builds/nVN6J2tFqNxOU4b4H/openapi.json
