Skip to content

EXIF & Metadata Stripper — Python source

View and strip GPS, camera, date, and software metadata from photos entirely in your browser. Download a clean copy.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""exif-stripper — EXIF / XMP / IPTC metadata reader + stripper for JPEG and PNG buffers.

Language: Python 3 (standard library only — struct, no PIL, no exifread).
CosmoDev polyglot showcase port of the `exif-stripper` tool, ported from
src/lib/exif-stripper.ts.

Why this file exists: every photo is a small surveillance report — GPS
coordinates, timestamps, serial numbers — embedded in standard metadata
segments. Both binary containers are parsed by hand with ``struct``, exactly
as the TS reference does, and stripping rebuilds the file *without* those
segments while copying image data byte-for-byte, so JPEG stripping is
lossless. Bytes objects stand in for the TS ArrayBuffer; every read is
bounds-checked so a corrupted file yields whatever parsed so far.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Optional

PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
EXIF_SIGNATURE = b"Exif\x00\x00"
XMP_SIGNATURES = (b"http://ns.adobe.com/xap/1.0/", b"http://ns.adobe.com/xmp/extension/")
IPTC_SIGNATURE = b"Photoshop 3.0\x00"


@dataclass
class ExifMetadata:
    """Everything the parser can surface, plus the rebuilt metadata-free image."""

    camera_make: Optional[str] = None
    camera_model: Optional[str] = None
    software: Optional[str] = None
    date_time: Optional[str] = None
    gps_latitude: Optional[float] = None  # decimal degrees, negative for S / W
    gps_longitude: Optional[float] = None
    image_width: Optional[int] = None
    image_height: Optional[int] = None
    orientation: Optional[int] = None  # EXIF orientation 1-8
    exposure_time: Optional[float] = None  # seconds (0.004 = 1/250 s)
    f_number: Optional[float] = None
    iso: Optional[int] = None
    focal_length: Optional[float] = None  # millimetres
    stripped: bytes = b""  # input with every metadata segment removed


def format_gps_coordinate(degrees: list[float], ref: str) -> float:
    """Degrees/minutes/seconds + hemisphere reference -> signed decimal degrees."""
    deg, minutes, sec = (list(degrees) + [0.0, 0.0, 0.0])[:3]
    decimal = deg + minutes / 60 + sec / 3600
    return -decimal if ref in ("S", "W") else decimal


def is_jpeg(b: bytes) -> bool:
    return len(b) >= 2 and b[0] == 0xFF and b[1] == 0xD8


def is_png(b: bytes) -> bool:
    return b[:8] == PNG_SIGNATURE


def has_signature(b: bytes, off: int, sig: bytes) -> bool:
    return 0 <= off and off + len(sig) <= len(b) and b[off : off + len(sig)] == sig


# --- JPEG segment walk ----------------------------------------------------------


def collect_jpeg_segments(b: bytes) -> Optional[list[tuple[int, int, int, int]]]:
    """Walk length-prefixed markers from the SOI up to SOS/EOI.

    Returns (marker, start, end, payload_start) tuples, or None when the
    structure is corrupted mid-walk.
    """
    segments: list[tuple[int, int, int, int]] = []
    off = 2
    while off + 2 <= len(b):
        if b[off] != 0xFF:
            return None
        if b[off + 1] == 0xFF:  # padding fill byte before the real marker
            off += 1
            continue
        marker = b[off + 1]
        # Standalone markers carry no length field (TEM, RSTn, SOI, EOI).
        if marker == 0x01 or 0xD0 <= marker <= 0xD9:
            segments.append((marker, off, off + 2, off + 2))
            if marker == 0xD9:
                break
            off += 2
            continue
        if off + 4 > len(b):
            return None
        size = int.from_bytes(b[off + 2 : off + 4], "big")  # includes itself
        if size < 2 or off + 2 + size > len(b):
            return None
        segments.append((marker, off, off + 2 + size, off + 4))
        if marker == 0xDA:  # SOS - entropy data follows, no more segments
            break
        off += 2 + size
    return segments


def is_jpeg_metadata_segment(b: bytes, seg: tuple[int, int, int, int]) -> bool:
    marker, _, _, payload = seg
    if marker == 0xE1:
        return has_signature(b, payload, EXIF_SIGNATURE) or any(
            has_signature(b, payload, sig) for sig in XMP_SIGNATURES
        )
    # APP13 is IPTC ("Photoshop 3.0\0" + 8BIM records) - always metadata.
    return marker == 0xED and has_signature(b, payload, IPTC_SIGNATURE)


# --- TIFF / EXIF IFD parsing ----------------------------------------------------

# EXIF field type -> byte size per component.
TYPE_SIZE = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8}

TAG_IMAGE_WIDTH, TAG_IMAGE_HEIGHT, TAG_ORIENTATION = 0x0100, 0x0101, 0x0112
TAG_MAKE, TAG_MODEL, TAG_SOFTWARE, TAG_DATE_TIME = 0x010F, 0x0110, 0x0131, 0x0132
TAG_EXIF_IFD_POINTER, TAG_GPS_IFD_POINTER = 0x8769, 0x8825
TAG_EXPOSURE_TIME, TAG_F_NUMBER, TAG_ISO = 0x829A, 0x829D, 0x8827
TAG_DATE_TIME_ORIGINAL, TAG_FOCAL_LENGTH = 0x9003, 0x920A
TAG_GPS_LAT_REF, TAG_GPS_LAT = 0x0001, 0x0002
TAG_GPS_LON_REF, TAG_GPS_LON = 0x0003, 0x0004

TYPE_ASCII, TYPE_SHORT, TYPE_LONG, TYPE_RATIONAL = 2, 3, 4, 5


class Tiff:
    """A TIFF block plus the byte order taken from its BOM."""

    def __init__(self, raw: bytes):
        self.raw = raw
        self.little = raw[:2] == b"II"  # "II" little-endian, "MM" big-endian
        self.ok = raw[:2] in (b"II", b"MM")

    def u16(self, off: int) -> int:
        return int.from_bytes(self.raw[off : off + 2], "little" if self.little else "big")

    def u32(self, off: int) -> int:
        return int.from_bytes(self.raw[off : off + 4], "little" if self.little else "big")


def value_offset(t: Tiff, entry: int, ftype: int, count: int) -> int:
    """Inline value field when it fits in 4 bytes, else the recorded offset."""
    size = TYPE_SIZE.get(ftype, 1) * count
    off = entry + 8 if size <= 4 else t.u32(entry + 8)
    return off if 0 <= off and off + size <= len(t.raw) else -1


def read_ascii(t: Tiff, entry: int, ftype: int, count: int) -> Optional[str]:
    if ftype != TYPE_ASCII or count < 1:
        return None
    off = value_offset(t, entry, ftype, count)
    if off < 0:
        return None
    text = t.raw[off : off + count].decode("utf-8", errors="replace").rstrip("\x00").strip()
    return text or None


def read_number(t: Tiff, entry: int, ftype: int, count: int) -> Optional[int]:
    if count < 1:
        return None
    off = value_offset(t, entry, ftype, count)
    if off < 0:
        return None
    if ftype == TYPE_SHORT:
        return t.u16(off)
    if ftype == TYPE_LONG:
        return t.u32(off)
    return None


def read_rationals(t: Tiff, entry: int, ftype: int, count: int) -> Optional[list[float]]:
    if ftype != TYPE_RATIONAL or count < 1:
        return None
    off = value_offset(t, entry, ftype, count)
    if off < 0:
        return None
    return [
        t.u32(off + i * 8) / t.u32(off + i * 8 + 4)
        if t.u32(off + i * 8 + 4) != 0
        else 0.0
        for i in range(count)
    ]


def parse_tiff(tiff_bytes: bytes, meta: ExifMetadata) -> None:
    t = Tiff(tiff_bytes)
    if len(tiff_bytes) < 8 or not t.ok or t.u16(2) != 42:
        return
    read_ifd(t, t.u32(4), meta)


def read_ifd(t: Tiff, offset: int, meta: ExifMetadata) -> None:
    if offset < 8 or offset + 2 > len(t.raw):
        return
    count = t.u16(offset)
    if offset + 2 + count * 12 > len(t.raw):
        return
    for i in range(count):
        entry = offset + 2 + i * 12
        tag, ftype, n = t.u16(entry), t.u16(entry + 2), t.u32(entry + 4)
        num = lambda: read_number(t, entry, ftype, n)  # noqa: E731
        rat = lambda: read_rationals(t, entry, ftype, n)  # noqa: E731

        def put(name: str, value: Any) -> None:
            if value is not None and getattr(meta, name) is None:
                setattr(meta, name, value)

        if tag == TAG_MAKE:
            put("camera_make", read_ascii(t, entry, ftype, n))
        elif tag == TAG_MODEL:
            put("camera_model", read_ascii(t, entry, ftype, n))
        elif tag == TAG_SOFTWARE:
            put("software", read_ascii(t, entry, ftype, n))
        elif tag in (TAG_DATE_TIME, TAG_DATE_TIME_ORIGINAL):
            put("date_time", read_ascii(t, entry, ftype, n))
        elif tag == TAG_IMAGE_WIDTH:
            put("image_width", num())
        elif tag == TAG_IMAGE_HEIGHT:
            put("image_height", num())
        elif tag == TAG_ORIENTATION:
            put("orientation", num())
        elif tag == TAG_ISO:
            put("iso", num())
        elif tag == TAG_EXPOSURE_TIME:
            put("exposure_time", (rat() or [None])[0])
        elif tag == TAG_F_NUMBER:
            put("f_number", (rat() or [None])[0])
        elif tag == TAG_FOCAL_LENGTH:
            put("focal_length", (rat() or [None])[0])
        elif tag == TAG_EXIF_IFD_POINTER:
            sub = read_number(t, entry, TYPE_LONG, 1)
            if sub is not None:
                read_ifd(t, sub, meta)
        elif tag == TAG_GPS_IFD_POINTER:
            gps = read_number(t, entry, TYPE_LONG, 1)
            if gps is not None:
                read_gps_ifd(t, gps, meta)


def read_gps_ifd(t: Tiff, offset: int, meta: ExifMetadata) -> None:
    if offset < 8 or offset + 2 > len(t.raw):
        return
    count = t.u16(offset)
    if offset + 2 + count * 12 > len(t.raw):
        return
    lat_ref, lon_ref = "N", "E"
    lat: Optional[list[float]] = None
    lon: Optional[list[float]] = None
    for i in range(count):
        entry = offset + 2 + i * 12
        tag, ftype, n = t.u16(entry), t.u16(entry + 2), t.u32(entry + 4)
        if tag == TAG_GPS_LAT_REF:
            lat_ref = (read_ascii(t, entry, ftype, n) or lat_ref)[:1].upper()
        elif tag == TAG_GPS_LON_REF:
            lon_ref = (read_ascii(t, entry, ftype, n) or lon_ref)[:1].upper()
        elif tag == TAG_GPS_LAT:
            lat = read_rationals(t, entry, ftype, n)
        elif tag == TAG_GPS_LON:
            lon = read_rationals(t, entry, ftype, n)
    if lat and meta.gps_latitude is None:
        meta.gps_latitude = format_gps_coordinate(lat, lat_ref)
    if lon and meta.gps_longitude is None:
        meta.gps_longitude = format_gps_coordinate(lon, lon_ref)


# XMP is XML; the only field surfaced is the creator tool / software.
def parse_xmp(payload: bytes, meta: ExifMetadata) -> None:
    import re

    match = re.search(rb":(?:CreatorTool|Software)>([^<]+)<", payload)
    if match and meta.software is None:
        meta.software = match.group(1).decode("utf-8", errors="replace").strip()


# --- JPEG / PNG parse ------------------------------------------------------------


def parse_jpeg(b: bytes, meta: ExifMetadata) -> None:
    for seg in collect_jpeg_segments(b) or []:
        marker, start, end, payload = seg
        if marker == 0xE1:
            chunk = b[payload:end]
            if has_signature(b, payload, EXIF_SIGNATURE):
                parse_tiff(chunk[len(EXIF_SIGNATURE) :], meta)
            elif any(has_signature(b, payload, sig) for sig in XMP_SIGNATURES):
                parse_xmp(chunk, meta)
        elif (
            0xC0 <= marker <= 0xCF
            and marker not in (0xC4, 0xC8, 0xCC)
            and end - payload >= 5
        ):
            # Start-of-frame header: precision(1), height(2), width(2), big-endian.
            meta.image_height = meta.image_height or int.from_bytes(b[payload + 1 : payload + 3], "big")
            meta.image_width = meta.image_width or int.from_bytes(b[payload + 3 : payload + 5], "big")


def parse_png(b: bytes, meta: ExifMetadata) -> None:
    off = 8
    while off + 8 <= len(b):
        length = int.from_bytes(b[off : off + 4], "big")
        if length > len(b) - off - 12:
            break  # corrupted chunk
        ctype = b[off + 4 : off + 8].decode("latin-1")
        data = b[off + 8 : off + 8 + length]
        if ctype == "IHDR":
            meta.image_width = meta.image_width or int.from_bytes(data[0:4], "big")
            meta.image_height = meta.image_height or int.from_bytes(data[4:8], "big")
        elif ctype in ("tEXt", "iTXt"):
            parse_png_text_chunk(ctype, data, meta)
        elif ctype == "eXIf":
            parse_tiff(data, meta)
        if ctype == "IEND":
            break
        off += 12 + length


def parse_png_text_chunk(kind: str, data: bytes, meta: ExifMetadata) -> None:
    nul = data.find(b"\x00")
    if nul < 1 or data[:nul] != b"Software":
        return
    if kind == "tEXt":
        text = data[nul + 1 :]
    else:
        # iTXt: keyword\0 compressionFlag(1) method(1) langTag\0 translated\0 text.
        if data[nul + 1] != 0:
            return  # compressed - not read
        pos = nul + 3
        for _ in range(2):  # skip the language tag and the translated keyword
            nxt = data.find(b"\x00", pos)
            if nxt < 0:
                return
            pos = nxt + 1
        text = data[pos:]
    value = text.decode("utf-8", errors="replace").strip()
    if value and meta.software is None:
        meta.software = value


# --- strip -----------------------------------------------------------------------


def strip_jpeg(b: bytes) -> bytes:
    segments = collect_jpeg_segments(b)
    if segments is None:
        return bytes(b)  # corrupted walk - copy verbatim
    parts = [b[:2]]
    for marker, start, end, _payload in segments:
        if marker == 0xDA:
            parts.append(b[start:])  # SOS header + entropy data + EOI, verbatim
            break
        if not is_jpeg_metadata_segment(b, (marker, start, end, _payload)):
            parts.append(b[start:end])
    return b"".join(parts)


def strip_png(b: bytes) -> bytes:
    parts = [b[:8]]
    off = 8
    while off + 8 <= len(b):
        length = int.from_bytes(b[off : off + 4], "big")
        if length > len(b) - off - 12:
            break
        ctype = b[off + 4 : off + 8]
        # tEXt / iTXt / eXIf are the metadata carriers; every other chunk
        # (IHDR, PLTE, IDAT, ...) is copied byte-for-byte, CRC included.
        if ctype not in (b"tEXt", b"iTXt", b"eXIf"):
            parts.append(b[off : off + 12 + length])
        off += 12 + length
    if off < len(b):
        parts.append(b[off:])
    return b"".join(parts)


# --- public API --------------------------------------------------------------------


def strip_metadata(data: bytes) -> bytes:
    """Rebuild the image without any metadata segment; lossless for JPEG."""
    if len(data) < 8:
        raise ValueError("File is too small to be a valid image.")
    if is_jpeg(data):
        return strip_jpeg(data)
    if is_png(data):
        return strip_png(data)
    raise ValueError("Unsupported format: only JPEG and PNG images are supported.")


def parse_metadata(data: bytes) -> ExifMetadata:
    """Read every supported metadata field, plus a stripped copy of the image."""
    if len(data) < 8:
        raise ValueError("File is too small to be a valid image.")
    if not is_jpeg(data) and not is_png(data):
        raise ValueError("Unsupported format: only JPEG and PNG images are supported.")
    meta = ExifMetadata(stripped=strip_metadata(data))
    if is_jpeg(data):
        parse_jpeg(data, meta)
    else:
        parse_png(data, meta)
    return meta

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →