How to Compress and Optimize AI-Generated Images (in Automated and Agent Workflows)
AI image generators emit large, lossless or near-lossless files at print-scale dimensions, so a single generated asset can weigh several megabytes before you have done anything with it. That is fine as a master, and wrong for the web. AI image compression is the step that turns a 3 MB generation into a sub-500 KB asset your page, app, or repo can actually ship.
Published July 2026 by the Mochify Engineering Team. This guide stays in the generated-asset and agent-pipeline lane: how to automate the optimize-after-generation step without leaking client data or blowing your agent's token budget.
What's in This Guide
Why AI-Generated Images Need Optimizing
AI image generators emit large, lossless or near-lossless files at print-scale dimensions, so a single generated asset can weigh several megabytes before you have done anything with it. That is fine as a master, and wrong for the web. AI image compression is the step that turns a 3 MB generation into a sub-500 KB asset your page, app, or repo can actually ship.
The numbers behind the problem are concrete. DALL-E 3 outputs at 1024x1024, 1024x1792, or 1792x1024, defaulting to PNG unless you explicitly ask for something else, and API users have reported 1024x1024 PNG responses landing at roughly 3 MB when compression is minimal. Midjourney V7 upscales its default 1:1 output to 2048x2048, a 4-megapixel canvas that produces multi-megabyte files if exported as PNG or high-quality JPEG without down-sampling. Stable Diffusion 1.5 generates at a native 512x512 and SDXL nearer 1024x1024, both of which are then routinely upscaled, compounding file weight at every stage if no optimization step exists.
Here is why that matters downstream. Images remain the single largest contributor to page weight, sitting at roughly 40% of total transfer size on a median page according to HTTP Archive data. A generated hero illustration dropped onto a page unoptimized is almost always the Largest Contentful Paint element, and Google's guidance is to keep LCP under 2.5 seconds, explicitly naming large, unoptimized images as a leading cause of slow LCP. A 3 MB above-the-fold PNG, on a mobile connection, is the difference between passing and failing Core Web Vitals.
There is a cost angle too. A pipeline that generates hundreds or thousands of images a week for content, listings, or experimentation pays for every megabyte in object storage and CDN egress. Keeping assets in the 2-4 MB band instead of the sub-500 KB range achievable with a resize-plus-modern-format step multiplies those bills across thumbnails, variants, and experiment branches that never needed to be stored at source resolution.
The Optimization Moves That Actually Matter
Three moves do almost all the work: pick a modern format, resize to the size you will actually display, and strip the metadata. Everything else is a refinement on top of these.
Format choice is the biggest lever
For generated imagery destined for the web, the priority order is AVIF, then WebP, with JPEG (via the jpegli encoder) and PNG as fallbacks. Google's WebP reference figures put lossless WebP at 26% smaller than PNG and lossy WebP at 25-34% smaller than JPEG at equivalent quality. AVIF, built on the AV1 codec, goes further: independent comparisons and web.dev's AVIF documentation describe roughly 50% reductions versus JPEG and 20-30% versus WebP at matched quality, with particular strength on the photographic detail and gradients common in diffusion output. A worked figure from a 2026 format comparison makes the magnitude tangible: a 2000x2000 image compressed from a 540 KB JPEG baseline to about 350 KB WebP (-35%) and 210 KB AVIF (-61%).
Browser support no longer holds you back. Per Can I Use, AVIF reached full support across Chrome, Edge, Firefox, Safari, and iOS Safari, covering well over 95% of global usage by 2025-2026, and WebP support is effectively universal. The safe delivery chain is AVIF with a WebP and then JPEG/PNG fallback, which <picture> elements and most image CDNs negotiate automatically. JPEG XL still has near-zero browser support outside Safari, so it stays an archival curiosity rather than a web delivery format for now.
Resize to the display size
Generators hand you a high-resolution canvas so you have room to crop, but the final embed is usually much smaller: 1200x630 for a social card, 800x800 for a product shot, 1600px on the long edge for a retina-friendly hero. Serving the source dimensions everywhere is the most common avoidable waste in a generated-image pipeline. A single oversized hero can consume more bandwidth than every other resource on the page combined.
Strip the metadata
EXIF, IPTC, and XMP fields carry nothing the browser needs to render an image, and removing them can trim 15-30% off the file with zero visual impact. For generated assets the payload is usually lighter than a DSLR's, but some pipelines embed tool identifiers or prompt traces, so stripping is both a size win and a way to avoid leaking internal detail.
Automating It: The Agent Tool-Call Pattern
The right way to automate image optimization in an agent pipeline is a tool call that takes a file path and returns a new path, never raw image bytes flowing through the model's context. This keeps the heavy, deterministic work in a dedicated process and leaves the agent to orchestrate.
The reason is token cost, and it is steep. Vision-enabled models bill images as token-heavy inputs. Claude's vision documentation gives the formula as approximately width * height / 750 tokens per image, which puts a 1-megapixel image at around 1,334 tokens and a 3000x2000 generation at roughly 8,000. Pass ten freshly generated images inline to kick off a batch and you have burned 80,000-plus tokens before any optimization has happened. On local models with 8k-32k context windows, a handful of inline images can exhaust the context entirely and the workflow simply stops working.
The Model Context Protocol formalizes the alternative. Tools are typed endpoints an agent invokes for side-effectful operations like file transformation, and the protocol's resource model is built around passing URI references such as file:///path/to/image.png rather than binary blobs. Anthropic's engineering write-up on code execution with MCP frames the payoff directly: moving heavy data and compute into dedicated tool processes lets the agent "use fewer tokens" while the model sees only references and summaries.
In practice that means an image-optimization capability should be exposed as a tool that accepts a path and returns the optimized path plus metadata (format, dimensions, compression ratio). The agent chains the steps - generate, optimize via tool call, then commit or publish - without ever holding pixels. For a pipeline handling dozens of images per job, designing it so only references live in context can cut token usage by orders of magnitude and makes execution far more predictable.
Three Real-World Workflows You Can Copy
There are three established shapes for the optimize-after-generation step, and most pipelines are a variation on one of them. Each separates generation from optimization so the compression logic is deterministic and reusable.
Workflow A: the content agent
An agent drafts an article, calls an image-generation API for illustrations, and publishes to a CMS. Each generated image is saved to a working directory, an optimization tool is called with the path and a preset (hero, inline, thumbnail), and the agent updates the CMS entry to point at the returned AVIF or WebP variant. The source PNG either moves to cold storage or is discarded. This is the workflow most teams building AI content pipelines actually need, and it is the one the Mochify section below walks through end to end.
Workflow B: the diffusion pipeline
Stable Diffusion or SDXL setups generate at model-native size, upscale to target resolution, apply brand or artistic filters, then call a compression step that produces sized AVIF/WebP derivatives and strips metadata. Those optimized files become the canonical production assets, and a CDN negotiates the final format per client via the Accept header. The principle is the same as a build pipeline: normalize and compress before anything reaches origin.
Workflow C: the repo build step
Teams that check generated assets into a repository can lean on CI. GitHub Actions such as calibreapp/image-actions traverse a pull request, recompress and transcode any new PNG/JPEG/WebP/AVIF, and commit the optimized versions back to the branch. An agent commits the raw generations as part of a content PR; CI enforces the size and format standard before merge. Agents generate, CI optimizes, humans review - clean separation of concerns.
The thread running through all three: the model decides what to generate and where it goes, and a dedicated tool decides how it gets compressed. That boundary is what makes the pipeline cheap to run and easy to reason about.
The Privacy Angle for Generated Client Assets
Where the optimization step sends your data matters the moment generated assets contain anything client-confidential, under NDA, or otherwise sensitive. The principle is data minimization, and it shapes which optimization tool you should reach for.
The UK ICO's guidance on data minimization requires that personal data be "adequate, relevant and limited to what is necessary," and its storage-limitation guidance adds that data should not be kept longer than needed. Applied to a generation pipeline, that argues against indefinitely storing the dozens of draft and discarded images a workflow throws off, and against routing client assets through a tool that retains them.
There is a quieter risk specific to agents. A local agent runtime with access to API keys and private repositories can, through a single misconfigured or undisclosed tool call, exfiltrate sensitive content to a remote service even when the model itself runs offline. "Local agent" does not imply "local data." Before adding an optimization tool to a privacy-sensitive workflow, it is worth asking what data enters the tool call, where exactly it goes, and whether the service retains it. For regulated or agency work, a zero-retention processor and a signed Data Processing Agreement are what turn that question into a documented answer.
Mochify Workflow: Optimizing Generated Images Inside an Agent
Mochify's local MCP server is built for the optimize-after-generation pattern: the agent describes the task in plain language, the tool handles the file, and only a file path comes back into context. No image bytes enter the model, so the context window stays clean no matter how many images the job touches. Here is the full setup.
- 1 Install the Mochify CLI
The same Rust binary serves as both the CLI and the local MCP server. Install via Homebrew:
brew install mochifyOn Linux, use the curl installer from github.com/getmochify/mochify-cli, or
cargo installfrom the repo. - 2 Authenticate once
Run
mochify auth login. A browser OAuth flow handles authentication and writes credentials to~/.config/mochify/credentials.toml. Both the CLI and the local MCP server pick them up automatically. - 3 Wire the local MCP server into your agent host
For Claude Desktop, add a short JSON snippet to
claude_desktop_config.json:{ "mcpServers": { "mochify": { "command": "mochify", "args": ["serve"] } } }For Claude Code:
claude mcp add mochify mochify serve - 4 Describe the task with Magic Flow
Magic Flow is Mochify's natural-language interface, so the agent describes the goal rather than setting format, quality, and resize values by hand. The two-step pipeline parses the prompt with a language model, then hands off to Mochify's C++ engine for the actual compression. Prompts that map cleanly onto a generated-image workflow:
- "Convert every PNG in
/build/generatedto AVIF at web quality, max 1600px wide" - "Compress these illustrations, strip metadata, and output WebP"
- "Resize this hero to 1200x630 and convert to AVIF for the social card"
Magic Flow is available in the web app, via the REST API at
POST /v1/prompt, through the CLI with the-pflag, and on both MCP surfaces. Direct (non-prompt) image compression runs throughPOST /v1/squish. Supported formats span JPG/jpegli, PNG, WebP, AVIF, JPEG XL, and HEIC/HEIF on upload, with batches up to 25 on paid tiers. - "Convert every PNG in
- 5 Receive file paths, not bytes
The local MCP server returns file paths and metadata: the optimized output path, format, dimensions, and compression ratio. No image data enters the agent's context. This is what makes high-volume batch processing viable, including on local hardware where context windows are tight.
MCP and API access are included on every tier, Free included (25 images per month, or 3 per session with no signup). For heavier batch work, Seller at $7.99/month raises that to 300 images and 25-file batches. Current limits are on the pricing page.
Cheat Sheet: AI Image Optimization at a Glance
| Decision | Default for generated images | Why |
|---|---|---|
| Delivery format | AVIF, with WebP then JPEG/PNG fallback | ~50% smaller than JPEG, 20-30% smaller than WebP at matched quality |
| Master/source format | PNG | Lossless, alpha, pixel-exact for re-edits |
| Target dimensions | Resize to display size (e.g. 1600px long edge, 1200x630 social) | Source-resolution everywhere is the biggest avoidable waste |
| Metadata | Strip EXIF/IPTC/XMP | 15-30% smaller, no visual change, no leaked internal detail |
| Where bytes go in an agent | File path in, file path out (never inline pixels) | A 1 MP image is ~1,334 tokens; inline batches blow the context |
| Automation surface | Tool call via MCP / CI build step / CDN | Deterministic, repeatable, observable |
| JPEG XL | Skip for web delivery | Near-zero browser support outside Safari |
| Client/NDA assets | Zero-retention processor + DPA | Data minimization; avoid third-party retention |
FAQ
Why are AI-generated images so large by default?
What format should I convert AI images to for the web?
<picture> element or an image CDN that negotiates by Accept header.How much smaller can compressing a generated PNG actually make it?
Why shouldn't I pass generated images straight into my agent's context?
width * height / 750 tokens per image, so a 1-megapixel image is about 1,334 tokens and ten of them exceed 13,000 before any work starts. The efficient pattern is an MCP tool that takes a file path and returns a new path, keeping pixels out of the model entirely.How do I automate image optimization in an AI pipeline?
Does Mochify's local MCP server keep my generated images private?
api.mochify.app over HTTPS, are processed in RAM, and are wiped immediately with no source disk writes and no logs containing file data. The local binary is a client over that API, not a local encoder, so the accurate claim is zero-retention rather than "never leaves your machine." Because the local path uses no pickup store, compressed bytes return straight to your disk, end to end.Can I optimize generated images and PDFs in the same agent workflow?
POST /v1/pdf endpoint: extract pages as PNG/JPEG/WebP, or split a multi-page PDF into single pages, all Magic Flow-capable. Video is the exception: it is processed client-side in the web app only, so keep video out of CLI, MCP, and API workflows.Is AVIF or JPEG XL the better choice for archiving my source generations?
Put the optimize-after-generation step on autopilot
Wire the local MCP server into your agent and describe the job in plain English: "convert every PNG in /build/generated to AVIF at web quality, max 1600px wide."
Try it free at mochify.app →Related Guides
- On-Device AI Agents: Image and PDF Optimization for Local Workflows · The hardware and local-MCP context behind running these workflows on your own machine, and why local agents do not automatically mean local data.
- How the Mochify MCP Server Works: Hosted vs Local · A full comparison of the two MCP surfaces: the hosted server's five-minute URL pickup versus the local server's zero-retention file-path return.
- AI Agent Workflow Automation for Photographers · The same tool-call patterns applied to a photography post-processing pipeline: batch conversion, EXIF stripping, and delivery formatting.
- How to Use Mochify via MCP · Step-by-step setup for both MCP surfaces, with config examples for Claude Desktop and Claude Code.
- The 2026 Guide to Next-Gen Formats: WebP, AVIF, JPEG XL · The deep dive on format choice, benchmarks, and browser support behind the recommendations here.