DEV Community

Cover image for My Upload Endpoint Was Saving Files That Only an iPhone Could Open
Renhua Wei
Renhua Wei

Posted on

My Upload Endpoint Was Saving Files That Only an iPhone Could Open

A worker finished a job at 18:40 and sent the photos from his phone. I opened that job on my laptop the next morning, clicked the thumbnail, and got a grey box with a broken-file icon. Not an error page. Just nothing.

The access log said 200. The row in the database had a size on it. The file was on disk at 394104 bytes, which is not a small number, and nothing in that row looked wrong. It took me an embarrassing amount of time to accept the boring explanation: the upload had worked exactly as written, and the file was in a format my own machine could not display.

HEIC. iPhone original, the path that skips Safari's transcode — share sheet, or any browser that hands the bytes straight through. My intake route checked the mimetype and moved on, and for months that was enough because everything else arrived as JPEG.

Here are the two lines I trusted:

if not file.mimetype.startswith("image/"):
    return 415
ext = {"image/jpeg": ".jpg", "image/png": ".png"}.get(file.mimetype, ".jpg")
Enter fullscreen mode Exit fullscreen mode

I would have defended both in review. image/heic starts with image/, so it sailed through the gate I was quietly proud of. And the extension map has a default, so the HEIC bytes landed on disk as photo.jpg. Every layer said yes. The only thing that said no was the operating system of the person who had to look at the picture.

That one is on me, and it is a silly mistake in hindsight: I built a whitelist and then gave it a default.

Then the second one, which took longer to see because it looked like good engineering. The resize helper refused to write a file bigger than its input:

if not must_convert and len(out) >= len(src):
    return src, ext
Enter fullscreen mode Exit fullscreen mode

Sensible rule for a 4 MB phone JPEG — re-encoding it into a slightly bigger JPEG is pure loss. Terrible rule for HEIC, because "keep the original" there means "keep the one Windows can't open". For a while I was convinced the conversion itself was broken, because the sizes on the files I cared about never moved. The conversion was fine. My guard was voting to keep the unreadable file, and the log line I kept staring at — kept original, 394104B — was telling me exactly that while I read it as "already optimized".

The fix is one extra flag, but I only found it after the third embarrassment. I wanted a round-trip test, so I decoded a HEIC and tried to write it back out:

KeyError: 'HEIF'
Enter fullscreen mode Exit fullscreen mode

Not a permissions thing, not a path thing. pillow-heif==1.1.1 bundles libde265, which decodes HEVC and has no encoder in it. 1.1.1 is the last release with a cp39 wheel, so on Python 3.9 I can read HEIC and I cannot write it, full stop. The library I had picked for "support HEIC" supported half of it, and I found out by guessing.

Worth saying out loud: I generated my test fixture with pillow-heif 1.9.0 on my laptop while production had 1.1.1 pinned. Two versions, two behaviours, one of which I had never actually run. If the fixture loads and the assertion passes, you do not go looking for the encoder.

What went in and what came out, measured on the production interpreter with the pinned dependencies:

in out
394104 B HEIC, stored 2400×1800, EXIF orientation=6 161576 B JPEG, 1200×1600, upright
route tests through Flask test_client 11 passed in 5.11s
full local suite 169 passed, 2 xfailed in 91.08s

The orientation number matters more than it looks. Orientation=6 means the stored pixels are landscape and every viewer is supposed to rotate them on display. Decode and re-encode, and that tag is gone — if you don't apply the rotation yourself, the worker's upright photo comes back on its side, and he assumes the app is broken. The output above is 1200×1600 portrait, which is the only way I know the rotation actually landed.

The code that replaced the old guard:

try:
    import pillow_heif
    pillow_heif.register_heif_opener()
except ImportError:
    pillow_heif = None  # intake keeps working, just without HEIC

def photo_ext_for(mime):
    return {"image/jpeg": ".jpg", "image/png": ".png",
            "image/heic": ".heic", "image/heif": ".heif",
            "image/avif": ".avif"}.get(mime, "")
Enter fullscreen mode Exit fullscreen mode

No default extension any more — an unknown image type gets no extension and is rejected downstream instead of being quietly labelled .jpg. And HEIC/HEIF/AVIF always convert, bigger output or not: must_convert=True. A 380 KB file that nothing on the shop floor can open is not smaller than a 400 KB file that everything can open. It is just broken in a way that costs less disk.

The endpoint lives in wiplink, the small job-tracking app I run for workshops, and the intake route is shared, so a photo attached to a job, a note, or a delivery all take the same path. Which is the other reason I care: one bad format decision at intake gets copied into every feature that touches a file.

My take, and I'll take the argument: keeping the original when the re-encode comes out bigger is a footgun, not an optimisation. Size is the wrong tiebreaker — readability over byte count — and the moment a format your users' desktops can't read walks through the gate, that guard starts preserving the exact file nobody can use. I'd argue the only judgment that matters is whether the person on the other end can open it.

I've only measured this on one phone model and one pipeline, so treat the numbers as narrow.

What does your intake do when the re-encode comes out bigger — keep the source, like mine did? Python 3.9.2, pillow 11.3.0, pillow-heif 1.1.1 on this box. If you think original fidelity is worth a broken preview on Windows, I want the case where it actually paid off — comments are open. The tool I run is in my profile.

Top comments (6)

Collapse
 
sss_ec8db2b6aa43a4e969595 profile image
sss •

To your question: ours keeps the source only when it is the same format as the output, and it decides that by opening the bytes, not by trusting the mimetype or the extension. Roughly (Pillow + pillow-heif, in an image-tools backend I run):

data = reencode(src, out_format)
if len(data) >= len(src) and sniffed_format(src) == out_format:
    data = src  # same format and the re-encode only grew it: the upload is the honest answer
Enter fullscreen mode Exit fullscreen mode

So an already well-compressed JPEG comes back untouched, but a HEIC can never "win" the size comparison, because HEIC is not JPEG. Same conclusion as your must_convert, without a list of mimetypes to keep in sync.

Two details that bit us around that sniff:

  • "Keep the original format" resolves the same way: if the decoded format is not one browsers show (we treat JPEG, PNG, WebP and GIF as web formats), the output becomes JPEG, or PNG when the image has an alpha channel. Otherwise the transparent part of a HEIF or TIFF turns into whatever colour happens to be stored under it.
  • Phones also write MPO (a JPEG with extra frames appended), and Pillow reports it as MPO, not JPEG. Without aliasing MPO to JPEG, the same-format check says "different" and every one of those photos gets re-encoded and grows.
Collapse
 
dafili profile image
Renhua Wei •

Same gap from the other side: Pillow 13.0.0 still reports Image.MIME['MPO'] as image/mpo (JPEG is image/jpeg), so a same-format check that goes through im.get_format_mimetype() still says "different" even after you alias im.format — both layers need the alias. The size comparison also misses the case where the re-encode shrank but dropped metadata: Pillow only carries EXIF and ICC through if you pass exif=im.info.get('exif') and icc_profile=im.info.get('icc_profile') on save, so a 12% smaller file can come back with the orientation flag gone and no other symptom. Do you pass those over, or re-read the source when the sniff says same-format?

Collapse
 
sss_ec8db2b6aa43a4e969595 profile image
sss •

Good catch on the MIME layer. We compare only im.format after the MPO alias, never the MIME type, so that one doesn't bite us, but anyone going through get_format_mimetype() needs the alias in both places.

On metadata, the honest answer is that we pass neither, and your question found a real gap:

  • EXIF: dropped, and that is mostly fine for us. We run exif_transpose() before resizing, so the orientation is already in the pixels and a missing flag can't turn the photo back. For a public tool it also means GPS and camera serials don't ride along on a file someone is about to post.
  • ICC: this is the gap. We don't pass icc_profile, so an iPhone photo tagged Display P3 comes back untagged, viewers treat it as sRGB, and it looks a little duller. That is now on our fix list: carry the profile through on save, keep stripping EXIF. The one catch is the CMYK path, where we already convert through the embedded profile, so the old CMYK profile must not be re-attached to RGB output.

When the sniff says same format and the re-encode is bigger, we return the source bytes untouched, so that path keeps everything. It's only the "smaller re-encode wins" path that loses the profile.

Thread Thread
 
dafili profile image
Renhua Wei •

Agreed on the CMYK path — re-attaching a 4-channel profile to RGB output is the failure that opens fine and shifts colour in anything that actually reads ICC. Cheap guard before copying the blob:

from PIL import ImageCms
space = ImageCms.ImageCmsProfile(io.BytesIO(icc)).profile.xcolor_space.strip()
if space == img.mode:  # 'RGB' == 'RGB'
    save_kwargs["icc_profile"] = icc
Enter fullscreen mode Exit fullscreen mode

An iPhone D3 profile is still 'RGB ' there, so this check only stops the CMYK leak, it does not tell P3 from sRGB.

The P3 case is the one I'd put a test on, because nothing raises: iPhone JPEG in, WebP out, reopen and assert Image.open(out).info.get('icc_profile') is non-empty. That assertion fails today, and the output renders dull in colour-managed viewers, which gets read as "the compressor is bad" instead of "we dropped metadata".

Collapse
 
userxnom profile image
Abdullah Naseer •

This is the kind of bug report I wish more people wrote — every layer said yes (200 in the log, a row with a size, a file on disk at 394104 bytes) and the user still got a grey box with a broken-file icon. That gap between "the system thinks it worked" and "the person can't open it" is the whole story.

The whitelist with a default extension is the lesson I'll steal: image/heic sails through startswith("image/") and then quietly becomes photo.jpg. And your second bug is sneakier still — the "keep the original if the re-encode is bigger" rule read as good engineering until the log line "kept original, 394104B" turned out to mean "kept unopenable." A file nobody on the shop floor can open isn't smaller, it's just broken at a smaller size.

I also respect the honesty about the fixture: generated with pillow-heif 1.9.0 on your laptop while production was pinned to 1.1.1, which only decodes. That is exactly the class of bug that passes 169 tests and fails in front of a real worker.

To answer your question: I would keep the converted copy too — openability beats byte count every time. One thing I'm curious about: now that HEIC/HEIF/AVIF always convert, do you also sniff the actual magic bytes on intake, or is the declared mimetype still the gate? What would wiplink do with a file whose mimetype says JPEG but whose bytes say HEIC?

Collapse
 
dafili profile image
Renhua Wei •

Honest answer: no signature check — declared mimetype is still the gate, so a JPEG-labelled HEIC takes the JPEG branch, skips the forced conversion, and lands in the same grey box. The place to catch it is the decode you already run: Image.open() reports HEIF for those bytes whatever the header said, so when img.format disagrees with the declared type, believe the decode and let the extension follow it.