Stop One Image from Eating All Memory in Your OCR Upload API

uploads a file that is only a few megabytes in size, yet after decoding it may require far more memory than expected. Highly compressible images, in particular,

If your OCR upload API accepts images, a file of only a few megabytes can take far more memory than you expect once it is decoded. Highly compressible images make size estimates unreliable, so the file size on disk tells you little about what processing will cost.

This guide is for developers who run an upload endpoint and need to stop one oversized image from exhausting memory. It explains why byte limits alone fall short, which protections to keep, and how to explain rejections to users.

The sample code uses synthetic test data and was checked in an isolated environment. It does not guarantee results for every real file or product. Keep original copies of important files, and verify the boundaries and acceptance criteria in this guide before you process them.

How do you stop one image from exhausting memory in an OCR upload API? The short answer

Limit both the upload size and the pixel dimensions, keep Pillow's decompression-bomb protection switched on, and run decoding under memory, time and concurrency limits.

Your situationWhat to doWhy
Your endpoint accepts image uploadsEnforce a byte limit and a pixel-count limit togetherA few megabytes can decode to far more memory than expected
You want to silence Pillow's size warningsKeep MAX_IMAGE_PIXELS in place and set your own budgetSetting it to None removes an important line of defence
A legitimate large drawing is rejectedRoute it through a defined large-file workflowExceeding a budget does not make a file bad
Users need to know why a file was refusedReport whether pixels or bytes exceeded the thresholdThey can split pages, lower the capture resolution or pick a specialised method
You are adding OmniDoc to your pipelineAdd your own input pre-check before integrationYou get earlier feedback, but the pre-check does not replace platform restrictions

Don't switch off protection just to silence warnings

Pillow includes a pixel-count protection against potential decompression bombs. Setting MAX_IMAGE_PIXELS to None stops the warnings, but it also removes that defence. Instead:

  • Define budgets based on your business requirements.
  • Decide in advance which warnings should become rejections.

Reference: Decompression Protection Instructions for Pillow Images

An entry check backed by a reserved library

The following example shows a basic entry check.

from io import BytesIO
import warnings
from PIL import Image

def inspect(raw, max_bytes=4096, max_pixels=1000):
    if len(raw) > max_bytes:
        raise ValueError("upload byte budget")
    with warnings.catch_warnings():
        warnings.simplefilter("error", Image.DecompressionBombWarning)
        with Image.open(BytesIO(raw)) as im:
            if im.width * im.height > max_pixels:
                raise ValueError("pixel budget")
            im.load()
            return im.size

stream = BytesIO()
Image.new("RGB", (40, 30), "white").save(stream, format="PNG")
raw = stream.getvalue()
assert len(raw) < 4096
assert inspect(raw, max_pixels=1200) == (40, 30)
try:
    inspect(raw, max_pixels=1000)
except ValueError as exc:
    assert "pixel" in str(exc)
else:
    raise AssertionError("pixel budget not enforced")

The budget values in this example are for synthetic testing only. The example processes a single frame, so it does not account for:

  • total throughput across multi-frame images
  • encoder vulnerabilities
  • peak concurrent decoding rates

The official entry point also needs:

  • a frame-count limit
  • a cumulative-pixel limit
  • handling of untrusted files inside an isolated execution environment

Each control does a different job

No single control covers everything. Use the table below to see what each one constrains and what you still need to add.

ControlPrimarily constrainsStill needs to be supplemented with
Upload byte limitNetwork and storage overheadDecoding scale
Maximum number of pixels per pageCommon large-image risksMulti-frame accumulation scale
Memory and time limitsResources actually consumed during executionInterpretable error feedback
Concurrency limitTotal resource consumptionQueue and backpressure

A budget overrun is not the same as a bad file

Legitimate large engineering drawings can exceed the default budget. Don't disable your safeguards for them. Send them through a well-defined large-file workflow instead.

Tell users which limit they hit

When a file is refused, say exactly which threshold was exceeded. That helps users choose a next step:

  • Split the pages into smaller files.
  • Reduce the capture resolution and upload again.
  • Choose a specialised processing method for very large files.

Add a pre-check before your translation entry point

Your translation entry point should state input risks upfront. Adding your own input pre-check before integration with OmniDoc gives earlier feedback on large images that are not supported. The pre-check cannot replace the platform's own restrictions, and it does not mean the platform already implements every strategy in this guide. Think of it as a layer of assurance between upload and delivery.

🎯 Which approach fits you?

If you accept images from the public

Enforce both the byte limit and the pixel limit, and reject files that breach either one with a clear message.

If you process engineering drawings

Set a higher budget through a separate large-file workflow, and keep the default protections active for everything else.

If you are adding OmniDoc to an existing pipeline

Add an input pre-check before the integration, and keep the platform's own restrictions in place.

❓ FAQ

1. Why isn't a file-size limit enough?

A file of a few megabytes can decode to far more memory than its size suggests, especially if the image is highly compressible. You also need pixel-dimension limits and runtime memory limits.

2. Should I set MAX_IMAGE_PIXELS to None to stop warnings?

No. That setting removes an important line of defence. Define your own budgets and decide which warnings should become rejections.

3. What does the example code cover?

It shows a basic entry check on a single frame using synthetic budget values. It does not cover multi-frame throughput, encoder vulnerabilities or peak concurrent decoding.

4. What should I tell a user whose file is rejected?

Tell them whether the pixel or byte threshold was exceeded, so they can split pages, reduce the capture resolution or choose a specialised method.

📝 Summary

A few megabytes can hide a very large decoded image, so OCR upload endpoints need limits on bytes, pixels, memory, time and concurrency together. Keep Pillow's protection on, use a defined workflow for large legitimate files, and tell users exactly which limit they hit.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-04