跳到正文
DEV Community· eden zhang·· 1 小時前AI 評分46

已下載的圖片為何會旋轉?解析 JPEG、WebP 和 AVIF 的方向資訊

Your Downloaded Images Are Sideways: Parsing EXIF Orientation in JPEG, WebP and AVIF

AI 導讀

JPEG、WebP 和 AVIF 以不同方式記錄圖片方向,像素本身未必已旋轉。JPEG 和 WebP 透過 EXIF Orientation 標籤記錄方向,AVIF 則使用 irot 和 imir;瀏覽器會在解碼時自動套用方向資訊。若轉換成 PNG 前未先把旋轉套用至像素,方向資訊便會遺失,導致圖片方向錯誤。

正文

Every image collector eventually ships a bug report that reads like this: "the images I downloaded are rotated 90 degrees." And every developer answers it once with "that's just how the camera saved it", and then spends three hours discovering that it is not that simple.

The pixels on disk are not rotated. The file declares a rotation. Two different consumers — your browser, your image viewer, your design tool — disagree about whether to apply that declaration, and the one that disagrees with your pipeline is the one your user opens first.

This post is about where that declaration lives, byte by byte, in JPEG, WebP and AVIF, what browsers actually do with it, and why "just rotate it afterwards" is a trap that produces double-rotated images in production.

The photo was never sideways

A modern phone camera has a sensor that is physically landscape. When you hold the phone upright, the sensor still records a 4032 × 3024 landscape frame; the firmware then writes Orientation = 6 into the EXIF block, meaning "the viewer should rotate this 90° clockwise to display it correctly". The JPEG bitstream is untouched. Decode it with an orientation-unaware decoder and you get a correctly-exposed, correctly-colored, sideways photo.

That single integer is the entire problem. It is also, in practice, the most common metadata field in the world of image tooling that gets dropped, duplicated, or applied twice.

Where the flag lives: JPEG

JPEG is a marker stream. FF D8 (SOI) starts the file, then a sequence of segments, each introduced by FF plus a marker byte and, for most markers, a two-byte big-endian length that includes the length field itself.

EXIF rides in an APP1 segment (FF E1). Its payload begins with the six-byte signature 45 78 69 66 00 00 ("Exif\0\0"), followed by a TIFF structure:

  • a two-byte byte-order mark: II (0x4949) little-endian or MM (0x4D4D) big-endian
  • a two-byte magic 0x002A
  • a four-byte offset to the first image file directory (IFD0)

An IFD is a two-byte entry count followed by 12-byte entries. Each entry is tag (2 bytes), type (2 bytes), count (4 bytes), and a four-byte value-or-offset field. Orientation is tag 0x0112, type 3 (SHORT), count 1 — so the value lives in the first two bytes of the value field, and you have to read it with the endianness you detected from the II/MM mark.

That is roughly fifteen lines of parsing. The hard part is not parsing, it is knowing that you must:

  1. scan for APP1 rather than assuming it is the first segment after SOI (it usually is, but APP0 JFIF and APP2 ICC profiles can precede it),
  2. stop scanning at the first SOS marker (FF DA), because after that you are in entropy-coded scan data where FF bytes appear constantly and any marker-walking logic will start hallucinating,
  3. read the value with the correct endianness, because half the cameras in the world write big-endian and the rest write little-endian.

The eight defined values and their intended transforms:

1 = no transform (storage orientation)
2 = mirror horizontal
3 = rotate 180
4 = mirror vertical
5 = transpose (mirror horizontal + rotate 270 CW)
6 = rotate 90 CW
7 = transverse (mirror horizontal + rotate 90 CW)
8 = rotate 270 CW

Values 5 through 8 involve a transpose, which is why naive implementations that only special-case 1, 3, 6 and 8 quietly mangle every mirrored selfie.

WebP and AVIF do it differently, which is the part that bites

WebP is a RIFF container: RIFF, a four-byte size, WEBP, then chunks identified by four-character codes. If the file carries EXIF, it is in a chunk with the fourcc EXIF, and — this is the detail that trips up JPEG-trained parsers — the chunk payload starts directly with the TIFF header. There is no Exif\0\0 signature to skip. Read the chunk body, detect II/MM, walk IFD0, read tag 0x0112.

AVIF is not a metadata container at all. It is ISOBMFF, a tree of boxes, and orientation is expressed as a transformative property rather than a tag:

  • irot (image rotation): a one-byte angle field where the lower two bits hold the angle in anticlockwise units of 90°.
  • imir (image mirror): a one-byte axis field, 0 meaning the vertical axis, 1 meaning the horizontal axis.

Both boxes live inside meta → iprp → ipco, referenced from the item property association list. A file can carry an irot and an imir together, applied in order, and HEIF-derived encoders use clap (clean aperture) on top of that. So an AVIF pipeline that reads EXIF only will report "no orientation" for a file that is genuinely rotated, because the rotation was never in EXIF.

To make this worse, browsers apply AVIF irot/imir during decode with no CSS involvement at all. The displayed image is correct, the decoded pixels are correct, and your metadata-only reader is the only component in the chain that is wrong.

What the browser actually does

Here is the behavior that makes pipelines inconsistent:

  • <img src> applies orientation automatically. The CSS property image-orientation defaults to from-image, which means the browser reads the EXIF flag and rotates at paint time. Since Chrome 81 this has been the default across all major browsers.
  • createImageBitmap(blob) also defaults to imageOrientation: "from-image". Passing "none" gives you the raw, stored-orientation pixels — which is exactly what you want for a hash or a thumbnail you will rotate yourself, and exactly what you do not want if you forgot the option exists.
  • canvas.drawImage(htmlImageElement, ...) draws already-oriented pixels, because the element decoded them that way.
  • PNG has no orientation semantics. The eXIf chunk exists in the PNG extensions spec, but browsers do not apply it. Once you transcode a rotated JPEG to PNG, the rotation information is gone unless you baked it into the pixels.

That last point is the trap. A pipeline that says "read EXIF, rotate the image afterwards" works for JPEG and silently produces upside-down PNGs, because by the time the file is PNG the evidence has been re-encoded away. The correct order is: decode in stored orientation (imageOrientation: "none"), apply the transform to a canvas, then encode. Bake first, write second. Never write an EXIF flag you are not sure the next consumer honors.

And never do both. A surprising number of exported files carry Orientation = 6 and rotated pixels, because two stages of the pipeline each "fixed" it. The file looks right in a viewer that ignores EXIF and sideways in the one that honors it.

The cost of getting it right

Three practical costs, each of which shapes the design:

Byte access. EXIF for JPEG sits near the front of the file, usually within the first 64 KB, so a Range: bytes=0-65535 request is enough and you can skip the full download. But a SOS can arrive later than 64 KB on images with large embedded thumbnails, and some CDNs answer 200 and send the whole body anyway. So you stream, cap the buffer, and bail out with "orientation unknown" instead of downloading 8 MB to find one integer.

Re-encoding. Baking rotation means decoding to a bitmap, transforming, and re-encoding. For a 200-image export that is real CPU time and a real quality decision: re-encoding a JPEG at quality 92 costs you a generation of artifacts. Tools that care store the transform as an editing instruction and apply it once, at export.

Privacy. The same EXIF block that carries orientation also carries GPS coordinates, camera make and model, body serial number, lens serial, DateTimeOriginal, and often a thumbnail of whatever the photo looked like before it was cropped. A batch downloader that "keeps the metadata intact" is redistributing location data with every file. Stripping EXIF entirely is the safe default for anything leaving the machine; keeping it is a deliberate choice for archives that need provenance.

What OmniPic does with this

This is the layer OmniPic AI Studio Pro is built around, and it is the reason the export path looks more complicated than a zip of URLs.

When a full-site inspection finishes, every collected image has been through: header-based dimension and format detection, orientation resolution (EXIF tag 0x0112 for JPEG and WebP, irot/imir for AVIF), and a decision record for whether the transform must be baked. On export, rotated images are decoded in stored orientation, transformed on a canvas, and re-encoded — so what lands in your reference library is upright in every viewer, not just in the one you happened to test.

The parts that are already handled:

  • Full-site image inspection with classification — one pass over the page collects image elements, CSS backgrounds, srcset candidates and lazy-loaded sources, then groups them by source and type.
  • CDN original recovery — Alibaba OSS, Tencent COS and Qiniu thumbnail URLs are reverse-mapped to the original asset.
  • On-device AI reverse image search — a MobileNet backbone produces a 1024-dimension feature vector, accelerated with WebGPU; nothing leaves the browser.
  • pHash visual deduplication — perceptual hashing collapses near-identical variants into one entry before download.
  • Direct Eagle and Billfish integration — collected assets land in the reference manager you already use, upright and with sensible metadata.
  • Streaming ZIP export for 2,000+ images — a streaming archive writer keeps memory flat, so a huge export does not freeze the browser.
  • 100% local processing — decoding, rotating, hashing, embedding and packaging all run in your browser; no upload, no account.

The configuration surface for this — orientation baking, metadata policy, deduplication thresholds — looks like this:

OmniPic AI Studio Pro — pro engine settings for orientation, metadata and deduplication

And the export view, where the baked-in orientation and metadata policy decide what the ZIP actually contains:

OmniPic AI Studio Pro — batch export with Eagle integration and streaming ZIP

OmniPic AI Studio Pro is available on all three major stores: Chrome, Edge, and Firefox. Install it here:

https://chromewebstore.google.com/detail/omnipic-studio-pro/cokoeaaaglgcljahaffjeijomhmkljlc

If you are building your own collector, take the small piece even if you never install anything: read tag 0x0112 before you touch a pixel, decide whether the transform is baked or declared, and never do both. Orientation is fifteen lines of parsing and about four hours of debugging if you skip it.

來源:DEV Community · dev.to