DEV Community

GoToolsOnline
GoToolsOnline

Posted on

Removing EXIF from a JPEG without re-encoding it: how the metadata is actually stored

A JPEG is just a sequence of marker segments: FFD8 (start of image), then a run of APPn segments, then the quantization tables (DQT), frame header (SOF), Huffman tables (DHT), and finally the scan (SOS) and FFD9 (end of image). Once you know that, removing metadata without touching the pixels is easy.

Where the metadata lives

  • EXIF is in an APP1 segment (FFE1) that starts with Exif\0\0, followed by a TIFF structure of tags.
  • XMP is a second APP1 segment that starts with http://ns.adobe.com/xap/1.0/.
  • IPTC sits in APP13 (the "Photoshop 3.0" block).
  • GPS is a sub-IFD inside EXIF. Latitude is three rationals (degrees, minutes, seconds) plus an N/S reference, and longitude works the same way with E/W.
  • ICC colour profile is in APP2. This one is not privacy-sensitive, and you want to keep it.

Why not just redraw on a canvas?

canvas.toBlob() does drop metadata, but it decodes and re-encodes the image. You lose quality, and you lose the ICC profile, so colours can shift.

Walking the segments

Every segment after SOI has a marker and a 2-byte big-endian length, so you can copy the file byte for byte and just skip the segments you don't want:

function stripMetadata(buffer) {
  const view = new DataView(buffer);
  const parts = [buffer.slice(0, 2)]; // FFD8
  let pos = 2;
  while (pos + 4 <= view.byteLength) {
    const marker = view.getUint16(pos);
    if (marker === 0xFFDA) break; // start of scan: copy the rest as-is
    const len = view.getUint16(pos + 2) + 2;
    const isExifOrXmp = marker === 0xFFE1;
    const isIptc = marker === 0xFFED;
    if (!isExifOrXmp && !isIptc) parts.push(buffer.slice(pos, pos + len));
    pos += len;
  }
  parts.push(buffer.slice(pos)); // scan data + FFD9
  return new Blob(parts, { type: 'image/jpeg' });
}
Enter fullscreen mode Exit fullscreen mode

Because nothing is decoded, the pixels are identical and there is zero quality loss.

Gotchas

  • Orientation is stored in EXIF. If you strip it, rotate the pixels first, or the photo may show up sideways. Reading the orientation tag before dropping APP1 is worth it.
  • PNG keeps metadata in eXIf, tEXt and iTXt chunks, and WebP keeps it in EXIF and XMP RIFF chunks, so the same idea works there with a different container walk.
  • Check the result by loading the output in an EXIF viewer.

I run GoToolsOnline; its image metadata tool does exactly this in the browser (view EXIF/GPS/XMP/IPTC, remove all or location only, keeps ICC/orientation): https://gotoolsonline.com/tools/image-metadata

Top comments (0)