# Image Compressor & Resizer API: Target KB, WebP (`ferrolark/image-compress-resize`) Actor

Image compressor and resizer: shrink images from URLs or base64, resize by width or height, compress to a target size in KB, and convert to WebP or AVIF. EXIF stripped. Before/after bytes per file. $0.002 per image.

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

## Pricing

$2.00 / 1,000 image processeds

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 Compress & Resize: Target KB, Width, WebP & AVIF API

Make images smaller with one API call:

- **Resize** by width and/or height. There are four fit modes, and images are never upscaled unless you allow it.
- **Compress to a target size**, for example "under 250 KB". The Actor searches for the highest quality that fits.
- **Convert while compressing** to WebP or AVIF, or keep the original format.
- **Strip EXIF** (GPS location, camera data) while keeping the color profile.
- **Before/after manifest** per file (bytes, % saved, dimensions, quality used, SHA-256), plus a ZIP.

It accepts URLs or base64 (n8n and Make binaries) and works with PNG, JPEG, WebP, AVIF, HEIC, GIF, TIFF, BMP and SVG.

### Real example

A 14.7 MB, 10109×4542 panorama from Wikimedia, resized to 1600 px wide with a 250 KB cap:

```json
{
  "imageUrls": ["https://upload.wikimedia.org/wikipedia/commons/3/3f/Fronalpstock_big.jpg"],
  "width": 1600,
  "targetKB": 250
}
```

- Result: `Fronalpstock_big.jpg`, 1600×719, **208,491 bytes (98.6% smaller)**, JPEG quality 82.
- Run time: 6.1 s on Apify at 1,024 MB, including downloading 14.7 MB.
- Platform usage: $0.0006.
- Your cost: **$0.002**.

```json
{
  "fileName": "Fronalpstock_big.jpg",
  "mimeType": "image/jpeg",
  "bytes": 208491,
  "sha256": "e7a64c72025855e99d51e3d2b9925a280b0d174c54db20e5081c7868db8f202b",
  "downloadUrl": "https://api.apify.com/v2/key-value-stores/<store-id>/records/Fronalpstock_big.jpg",
  "inputFormat": "jpeg",
  "inputBytes": 14679474,
  "inputWidth": 10109,
  "inputHeight": 4542,
  "format": "jpeg",
  "width": 1600,
  "height": 719,
  "quality": 82,
  "savedPercent": 98.6,
  "keptOriginal": false,
  "targetReached": true
}
```

In a local test of the same engine, the 224 KB Wikimedia transparency-demo PNG converted to WebP at 800 px with a 60 KB target came out at 61,356 bytes (quality 38, 72.7% smaller). The alpha channel was kept.

### Price and limits

- **$0.002 per processed image.** The ZIP is free. Failed files are not charged.
- Limits:
  - 50 images and 100 MB per run;
  - 50 megapixels per input image;
  - output up to 10,000 px per side.
- The target-size search covers quality 30 up to your `quality` setting (default 82). If even quality 30 is too big, you get the smallest result and `targetReached: false` with a warning. Reduce the dimensions, or switch to WebP or AVIF.

### Input

| Field | Default | What it does |
|---|---|---|
| `imageUrls` / `files` | none | URLs, or `[{"base64": "...", "name": "..."}]`. |
| `width`, `height` | none | Target box. With only one of them, the aspect ratio is kept. |
| `fit` | `inside` | `inside` keeps the ratio within the box; `cover` fills and crops the center; `contain` pads with the background; `fill` stretches. |
| `allowUpscale` | `false` | Allow enlarging small images. |
| `targetKB` | none | Maximum output size in KB (lossy formats). |
| `quality` | 82 | Quality, or the upper bound of the target search. |
| `format` | `keep` | Keep the format, or convert to WebP, AVIF, JPEG, PNG, HEIC, TIFF, GIF or BMP. |
| `onlyIfSmaller` | `true` | If nothing but re-compression was asked and the result isn't smaller, return the original bytes. |
| `backgroundColor`, `keepColorProfile`, `createZip`, `createShareableUrl` | | Same as in Image Convert. |

### Call it from code, n8n or an AI agent

**API (synchronous):**

```bash
curl -X POST "https://api.apify.com/v2/acts/ferrolark~image-compress-resize/run-sync-get-dataset-items?maxTotalChargeUsd=0.1" \
  -H "Authorization: Bearer $APIFY_TOKEN" -H "Content-Type: application/json" \
  -d '{"imageUrls": ["https://example.com/hero.png"], "width": 1200, "format": "webp", "targetKB": 150}'
```

**n8n:** paste this workflow on the canvas (Ctrl+V). Then add a Header Auth credential with the name `Authorization` and the value `Bearer <your Apify token>`, and use it in both HTTP nodes. The second node downloads the optimized image as a binary. To process binaries that are already in n8n, send them in `files` as base64.

```json
{
  "name": "Ferrolark image-compress-resize",
  "nodes": [
    {
      "parameters": {},
      "name": "When clicking Test workflow",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.apify.com/v2/acts/ferrolark~image-compress-resize/run-sync-get-dataset-items?maxTotalChargeUsd=0.05",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\"imageUrls\": [\"https://upload.wikimedia.org/wikipedia/commons/3/3f/Fronalpstock_big.jpg\"], \"width\": 1600, \"targetKB\": 250}",
        "options": {
          "timeout": 300000
        }
      },
      "name": "Run Actor",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.downloadUrl }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          }
        }
      },
      "name": "Download file",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        0
      ]
    }
  ],
  "connections": {
    "When clicking Test workflow": {
      "main": [
        [
          {
            "node": "Run Actor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run Actor": {
      "main": [
        [
          {
            "node": "Download file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
```

**Make / Zapier:** use the Apify app's "Run Actor" action with `ferrolark/image-compress-resize`.

**AI agents (MCP):** add `ferrolark/image-compress-resize` to the Apify MCP server (`https://mcp.apify.com?actors=ferrolark/image-compress-resize`).

### Use cases

- Meet upload limits: marketplaces, CMSs, email tools and forms that cap images at 200 KB or 1 MB.
- Shrink user uploads before storing them, without running ImageMagick yourself.
- Make thumbnails and social sizes, for example 1200×630 with `fit: cover`.
- Batch-optimize a site's images to WebP or AVIF for Core Web Vitals.

### Troubleshooting

- **`targetReached: false`**: the size is too small for those dimensions. Lower `width`, or use `format: "webp"` or `"avif"`.
- **PNG stays big**: PNG is lossless, so `targetKB` cannot lower its quality. Resize it, or convert to WebP.
- **`keptOriginal: true`**: the original was already better compressed, so you got it back unchanged.

### Limitations

- No AI upscaling, cropping by face or object, or background removal.
- Animated images are processed from their first frame.

### Changelog

- **1.0** (November 2026): first release. Resize with four fit modes, target-KB search, format conversion, EXIF stripping, ZIP and before/after manifest.

### More Ferrolark tools

- [Brand Name Availability Checker](https://apify.com/ferrolark/brand-name-checker): domains, GitHub, npm, PyPI and more in one report.
- [Domain Intelligence Report](https://apify.com/ferrolark/domain-intelligence-report): WHOIS, DNS, email security, SSL and hosting for any domain.
- [Launch Asset Pack](https://apify.com/ferrolark/launch-asset-pack): favicons, PWA icons, OG image and head tags from one logo.
- [Live Deploy QA](https://apify.com/ferrolark/live-deploy-qa): meta tags, canonical, robots, OG image and favicon of your deployed routes, with diffs between deploys.
- [Sitemap Delta](https://apify.com/ferrolark/sitemap-delta): new, removed and broken URLs in any sitemap since the last run.
- [RSS Delta](https://apify.com/ferrolark/rss-delta): only new RSS, Atom and JSON Feed items, de-duplicated.
- [PDF Merge API](https://apify.com/ferrolark/pdf-merge-api): merge PDFs from URLs or base64 with page ranges and a SHA-256 manifest.
- [PDF Split API](https://apify.com/ferrolark/pdf-split-api): split a PDF by page ranges or every N pages, or extract pages, with a ZIP and manifest.
- [Image Convert](https://apify.com/ferrolark/image-convert): PNG, JPG, WebP, AVIF and HEIC conversion (SVG input too) from URLs or base64.
- [PDF to Image](https://apify.com/ferrolark/pdf-to-image): PDF pages to PNG, JPG or WebP at the DPI you choose.
- [Image to PDF](https://apify.com/ferrolark/image-to-pdf): JPG, PNG, HEIC and WebP images to one PDF, JPEGs embedded without recompression.
- [PDF Compress](https://apify.com/ferrolark/pdf-compress): smaller PDFs, lossless or with image downsampling; charged only when smaller.
- [HTML to PDF & URL to PDF](https://apify.com/ferrolark/html-to-pdf): web pages or raw HTML to PDF with headless Chrome.
- [Markdown to PDF](https://apify.com/ferrolark/markdown-to-pdf): Markdown with tables, code and footnotes to a clean PDF.
- [DOCX to PDF](https://apify.com/ferrolark/docx-to-pdf): Word, Excel, PowerPoint and ODT to PDF with LibreOffice.
- [Data Convert](https://apify.com/ferrolark/data-convert): CSV, JSON, NDJSON and Excel XLSX in any direction.

***

*Built by Ferrolark.*

# Actor input Schema

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

Public image URLs: PNG, JPEG, WebP, AVIF, HEIC/HEIF, GIF (first frame), TIFF, BMP or SVG. Up to 50 files and 100 MB per run.

## `files` (type: `array`):

For n8n/Make binaries: a list of {"base64": "...", "name": "photo.heic"} objects (or {"url": ...}). Keep the whole input under about 9 MB; use URLs for bigger batches.

## `width` (type: `integer`):

Target width. With only width or only height, the aspect ratio is kept.

## `height` (type: `integer`):

Target height.

## `fit` (type: `string`):

How to fit the image into width x height.

## `allowUpscale` (type: `boolean`):

By default images are never enlarged.

## `targetKB` (type: `number`):

Find the highest quality that fits under this size (JPEG, WebP, AVIF, HEIC). Example: 200 for a 200 KB cap.

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

Quality for lossy formats; with a target size, the upper bound of the search.

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

Keep the original format, or convert while compressing (WebP and AVIF usually save the most).

## `onlyIfSmaller` (type: `boolean`):

When no resize or format change is requested and re-encoding would not shrink the file, return the original bytes.

## `keepColorProfile` (type: `boolean`):

Keeps colors accurate for wide-gamut photos. EXIF metadata (GPS, camera) is always removed.

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

Used when transparent images are saved as JPEG/BMP, and for 'contain' padding.

## `createZip` (type: `boolean`):

Bundle all outputs in one ZIP (free).

## `createShareableUrl` (type: `boolean`):

Also return signed links that work without an Apify token. Anyone with a link can download that file.

## Actor input object example

```json
{
  "imageUrls": [
    "https://upload.wikimedia.org/wikipedia/commons/a/a9/Example.jpg"
  ],
  "files": [],
  "width": 800,
  "fit": "inside",
  "allowUpscale": false,
  "quality": 82,
  "format": "keep",
  "onlyIfSmaller": true,
  "keepColorProfile": true,
  "backgroundColor": "#ffffff",
  "createZip": true,
  "createShareableUrl": false
}
```

# Actor output Schema

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

No description

## `files` (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://upload.wikimedia.org/wikipedia/commons/a/a9/Example.jpg"
    ],
    "files": [],
    "width": 800
};

// Run the Actor and wait for it to finish
const run = await client.actor("ferrolark/image-compress-resize").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/a/a9/Example.jpg"],
    "files": [],
    "width": 800,
}

# Run the Actor and wait for it to finish
run = client.actor("ferrolark/image-compress-resize").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/a/a9/Example.jpg"
  ],
  "files": [],
  "width": 800
}' |
apify call ferrolark/image-compress-resize --silent --output-dataset

```

## MCP server setup

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

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/DaFUiLrKSeFHkOedW/builds/8LcvypS9kkPfGYUWv/openapi.json
