To convert logistics images into print formats through an API, reject bad geometry before spending bandwidth on OCR, retain the original only while a job can still be disputed, and accept an output only after reopening and validating its bytes. The least complex design is one upload, one normalized derivative, one OCR result, and a small manifest recording dimensions, color-profile presence, content digest, and every validation decision. Do not use a file extension or a nominal DPI field as proof that an image is printable.
Reject early.
The bill is made from uploaded bytes, stored byte-hours, derivative writes, downloads to OCR and conversion workers, and retries. Start with a planning model, not a provider price sheet:
def monthly_byte_traffic(*, uploads, source_bytes, normalized_bytes, source_reads, normalized_reads, retry_rate): base = uploads * (source_bytes * (1 + source_reads) + normalized_bytes * (1 + normalized_reads)) return int(base * (1 + retry_rate)) # Capacity assumptions, not benchmark results or provider prices. traffic = monthly_byte_traffic( uploads=10_000, source_bytes=12_000_000, normalized_bytes=2_000_000, source_reads=1, normalized_reads=2, retry_rate=0.03, ) print(f"{traffic / 1_000_000_000:.1f} GB/month") Under those explicit assumptions, source traffic contributes 240 GB before retries, while normalized-image traffic contributes 60 GB. The useful change is avoiding another read of the 12 MB source after normalization, not shaving a few bytes from a manifest. Your measurements may reverse the result, especially when OCR runs repeatedly or derivatives are larger. Instrument bytes by stage and recompute.
How should an API convert images into print formats?
Treat upload handling as a sequence of gates. First cap request bytes and decoded pixel count. Then decode the image rather than trusting its suffix, apply orientation, and compare pixel dimensions with the requested physical size. A 2400 by 3000 pixel image targeted at 8 by 10 inches yields 300 pixels per inch in both directions; the same pixels targeted at 16 by 20 inches yield 150. These are arithmetic examples, not universal quality thresholds. The printer or production owner must supply the acceptance threshold.
Color is a separate decision. Record whether an embedded profile exists and which output profile the print contract requires. Do not silently label unprofiled pixels as if their source color space were known. A pipeline may reject them, route them for review, or apply a documented assumption, but those outcomes are materially different and belong in the manifest. An image format's capabilities do not amount to a print-quality guarantee.
Unknown is not a color space.
Use a narrow contract between the upload API and workers. It should carry an immutable object identifier, a digest, pixel dimensions, intended size, required minimum pixels per inch, color-policy result, and status. OCR text belongs beside that record, not inside the print image. The API can return an accepted job identifier while conversion proceeds asynchronously, provided state transitions are monotonic and duplicate submissions with the same digest and settings resolve to the same work item.
Make validation executable
The validator below is independent of a decoder. A Node.js upload service can call its chosen image decoder, populate this structure, and send it to a worker or evaluate the same rules locally. Keeping the rule function free of codec behavior makes its boundary testable; actual decoded metadata, not client JSON, must populate DecodedImage.
from dataclasses import dataclass from decimal import Decimal @dataclass(frozen=True) class DecodedImage: width_px: int height_px: int encoded_bytes: int format_name: str has_embedded_profile: bool @dataclass(frozen=True) class PrintRequest: width_in: Decimal height_in: Decimal minimum_ppi: Decimal maximum_bytes: int require_profile: bool = True def validate(image: DecodedImage, request: PrintRequest) -> list[str]: errors: list[str] = [] if image.width_px <= 0 or image.height_px <= 0: errors.append("decoded dimensions must be positive") if request.width_in <= 0 or request.height_in <= 0: errors.append("physical dimensions must be positive") if image.encoded_bytes > request.maximum_bytes: errors.append("encoded input exceeds the request limit") if errors: return errors horizontal_ppi = Decimal(image.width_px) / request.width_in vertical_ppi = Decimal(image.height_px) / request.height_in if min(horizontal_ppi, vertical_ppi) < request.minimum_ppi: errors.append("insufficient pixels for requested physical size") if request.require_profile and not image.has_embedded_profile: errors.append("required embedded color profile is absent") return errors request = PrintRequest( width_in=Decimal("8"), height_in=Decimal("10"), minimum_ppi=Decimal("300"), maximum_bytes=15_000_000, ) image = DecodedImage(2400, 3000, 12_000_000, "JPEG", True) assert validate(image, request) == [] The example proves policy arithmetic. The decoder adapter still needs fixed fixtures for orientation metadata, truncated input, oversized decoded dimensions, unsupported formats, and profile extraction. A remote service or changing sample URL should not determine CI results.
After encoding, reopen the derivative and apply the geometric checks again. Verify its output format, byte limit, digest, and required profile too. This second decode catches failures an in-memory preflight cannot: truncated bytes, the wrong encoding, missing required metadata, or geometry that differs from the request. Success means the persisted artifact passes validation, not that a conversion process exited cleanly.
Where does bandwidth compete with OCR quality?
OCR needs legible glyph edges and enough pixels around small labels, while the transport budget rewards fewer bytes. One global compression setting cannot resolve that tension. A pallet label with dense small text, a wide loading-bay photograph with one large identifier, and a damaged shipping document impose different demands on the normalized derivative.
A useful evaluation set stores source images, target text, crop regions, requested print geometry, and failure labels. For each normalization policy, measure OCR acceptance against bytes transferred and decoded pixel count. Keep the policy only if it stays within the print gate and the operation's OCR error budget. No single metric is enough. A smaller file that changes a container identifier is a failure; a larger derivative that adds no accepted text is waste.
| Decision | Quality effect | Bandwidth effect | Failure to watch |
|---|---|---|---|
| Downscale before OCR | May remove small character detail | Usually reduces transferred and decoded data | Plausible but incorrect identifiers |
| Preserve source pixels | Retains available detail | Carries the largest object through later stages | Repeated source reads dominate traffic |
| Crop known label regions | Concentrates pixels on relevant text | Avoids transporting irrelevant scene area | Bad crop coordinates omit characters |
| Re-encode one normalized derivative | Makes downstream input consistent | Adds one write but can reduce later reads | Profile or orientation loss |
These are directional trade-offs, not guaranteed compression ratios. Measure with the cameras, labels, damage patterns, and print contracts actually in scope.
Measure both.
What should survive after the job closes?
Keep three clocks separate: operational retry, dispute or audit, and long-term analysis. During the retry window, the source may be necessary because a fixed converter or crop policy could produce a new derivative without asking for another upload. During a dispute window, the source and manifest can establish what arrived and which rules ran. Long-term model analysis may need a curated, authorized sample rather than every source image.
Deletion is architectural. Once the applicable retention window closes, remove the original and transient derivatives while retaining the smallest record that can still explain the decision: digest, dimensions, format, profile result, policy version, OCR status, output digest, and timestamps. The deliberate sacrifice is reprocessability. If a decoder defect is discovered after source deletion, the image cannot be reconstructed from its digest or OCR text; the system must request a new upload or accept that the historical job cannot be regenerated.
Indefinite source retention buys optionality but continues storage exposure and makes deletion obligations harder to reason about. Premature deletion reduces stored bytes but removes the strongest debugging artifact. Set each clock with legal, operational, and production owners, then enforce it as lifecycle policy.
Production acceptance should expose counts for rejection reason, input and output bytes, decoded pixels, conversion duration, retry count, and OCR acceptance by policy version. Alert on distributions and state transitions, not one average; an average can hide a tail of enormous scans or one camera model whose profile repeatedly disappears. Logs should identify objects by job identifier and digest, while avoiding extracted shipping text unless access and retention rules explicitly permit it.
Roll out policy changes against a frozen evaluation corpus first, then a bounded slice of live jobs. Compare OCR outcomes and byte traffic. Make rollback a policy-version change so accepted assets retain the rules that justified them. A team should be able to explain a rejection without rerunning mutable code.
The decision rule is compact: decode early, compute print geometry from pixels and physical dimensions, make color assumptions explicit, normalize once, validate again after persistence, and delete sources on a declared schedule. This does not maximize every quality metric. It creates an auditable boundary where additional bandwidth must purchase a measured improvement.
References
- MDN, Image file type and format guide: https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types

