Skip to content

EXIF & Metadata Stripper — Go source

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

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

// Package exifstripper ports src/lib/exif-stripper.ts
// (dual source: the web lib is TypeScript, the CLI lib is Go — kept in
// lock-step). Pure logic, no DOM, no external libraries: the JPEG and PNG
// binary formats are parsed directly. The table-driven tests in
// exif_stripper_test.go share vectors with src/lib/exif-stripper.test.ts so
// the two implementations are held to the same contract.
//
// Format coverage mirrors the TS lib exactly:
//   - JPEG: APP1 (0xFFE1) segments carrying "Exif\0\0" (a TIFF IFD structure,
//     big- or little-endian per the TIFF byte-order mark) or XMP, and APP13
//     (0xFFED) segments carrying IPTC ("Photoshop 3.0\0").
//   - PNG: tEXt / iTXt text chunks and the eXIf chunk (same TIFF structure).
//
// Stripping rebuilds the file without those metadata segments - the image
// data itself is copied byte-for-byte, so JPEG stripping is lossless.
package exifstripper

import (
	"bytes"
	"encoding/binary"
	"errors"
	"regexp"
	"strings"
)

// ExifMetadata is the Go twin of the TS ExifMetadata interface. Optional TS
// fields become pointers: nil means "absent". Stripped is always present - a
// rebuilt copy of the input with every metadata segment removed.
type ExifMetadata struct {
	CameraMake   *string
	CameraModel  *string
	Software     *string
	DateTime     *string
	GPSLatitude  *float64 // decimal degrees; negative for S/W hemispheres
	GPSLongitude *float64
	ImageWidth   *int
	ImageHeight  *int
	Orientation  *int // EXIF orientation value 1-8
	ExposureTime *float64
	FNumber      *float64
	ISO          *int
	FocalLength  *float64 // millimetres
	Stripped     []byte
}

// FormatGpsCoordinate converts degrees/minutes/seconds plus a hemisphere
// reference to signed decimal degrees. It mirrors formatGpsCoordinate() in
// src/lib/exif-stripper.ts.
func FormatGpsCoordinate(degrees []float64, ref string) float64 {
	var deg, min, sec float64
	if len(degrees) > 0 {
		deg = degrees[0]
	}
	if len(degrees) > 1 {
		min = degrees[1]
	}
	if len(degrees) > 2 {
		sec = degrees[2]
	}
	decimal := deg + min/60 + sec/3600
	if ref == "S" || ref == "W" {
		return -decimal
	}
	return decimal
}

// --- errors -------------------------------------------------------------------

var (
	// ErrTooSmall mirrors the TS "File is too small to be a valid image.".
	ErrTooSmall = errors.New("File is too small to be a valid image.")
	// ErrUnsupported mirrors the TS "Unsupported format: only JPEG and PNG
	// images are supported.".
	ErrUnsupported = errors.New("Unsupported format: only JPEG and PNG images are supported.")
)

// --- format detection ---------------------------------------------------------

var (
	exifSignature = "Exif\x00\x00"
	iptcSignature = "Photoshop 3.0\x00"
	xmpSignatures = []string{
		"http://ns.adobe.com/xap/1.0/",
		"http://ns.adobe.com/xmp/extension/",
	}
	pngSignature = []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}
)

func isJpeg(data []byte) bool {
	return len(data) >= 2 && data[0] == 0xff && data[1] == 0xd8
}

func isPng(data []byte) bool {
	return len(data) >= 8 && bytes.Equal(data[:8], pngSignature)
}

func hasSignature(data []byte, off int, sig string) bool {
	if off < 0 || off+len(sig) > len(data) {
		return false
	}
	for i := 0; i < len(sig); i++ {
		if data[off+i] != sig[i] {
			return false
		}
	}
	return true
}

// --- JPEG segment walk ----------------------------------------------------------

// jpegSegment describes one length-prefixed (or standalone) JPEG marker.
type jpegSegment struct {
	marker byte
	// start is the segment start (at the 0xFF byte); end is exclusive.
	start        int
	end          int
	payloadStart int // first payload byte (right after the 2-byte length field)
}

// collectJpegSegments walks length-prefixed markers from just after the SOI up
// to (and including) the SOS marker, whose entropy-coded data runs to the EOI.
// It returns nil when the structure is corrupted mid-walk.
func collectJpegSegments(data []byte) []jpegSegment {
	var segments []jpegSegment
	off := 2
	for off+2 <= len(data) {
		if data[off] != 0xff {
			return nil
		}
		if data[off+1] == 0xff {
			off++ // padding fill byte before the real marker
			continue
		}
		marker := data[off+1]
		// Standalone markers carry no length field (TEM, RSTn, SOI, EOI).
		if marker == 0x01 || (marker >= 0xd0 && marker <= 0xd9) {
			segments = append(segments, jpegSegment{marker, off, off + 2, off + 2})
			if marker == 0xd9 {
				break
			}
			off += 2
			continue
		}
		if off+4 > len(data) {
			return nil
		}
		size := int(binary.BigEndian.Uint16(data[off+2:])) // includes the 2 length bytes itself
		if size < 2 {
			return nil
		}
		end := off + 2 + size
		if end > len(data) {
			return nil
		}
		segments = append(segments, jpegSegment{marker, off, end, off + 4})
		if marker == 0xda {
			break // SOS - entropy data follows, no more segments
		}
		off = end
	}
	return segments
}

func isJpegMetadataSegment(data []byte, seg jpegSegment) bool {
	if seg.marker == 0xe1 {
		if hasSignature(data, seg.payloadStart, exifSignature) {
			return true
		}
		for _, sig := range xmpSignatures {
			if hasSignature(data, seg.payloadStart, sig) {
				return true
			}
		}
		return false
	}
	// APP13 is IPTC ("Photoshop 3.0\0" + 8BIM records) - always metadata.
	return seg.marker == 0xed && hasSignature(data, seg.payloadStart, iptcSignature)
}

// isSofMarker reports whether m is a start-of-frame marker (SOF0..SOF15 minus
// DHT/C4, JPG/C8, DAC/CC).
func isSofMarker(m byte) bool {
	return m >= 0xc0 && m <= 0xcf && m != 0xc4 && m != 0xc8 && m != 0xcc
}

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

// EXIF field types -> byte size per component.
var typeSizes = map[uint16]int64{
	1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8,
}

func typeSizeOf(typ uint16) int64 {
	if s, ok := typeSizes[typ]; ok {
		return s
	}
	return 1
}

// IFD0 tags.
const (
	tagImageWidth     = 0x0100
	tagImageHeight    = 0x0101
	tagMake           = 0x010f
	tagModel          = 0x0110
	tagOrientation    = 0x0112
	tagSoftware       = 0x0131
	tagDateTime       = 0x0132
	tagExifIfdPointer = 0x8769
	tagGpsIfdPointer  = 0x8825
	tagExposureTime   = 0x829a
	tagFNumber        = 0x829d
	tagISO            = 0x8827
	tagDateTimeOrig   = 0x9003
	tagFocalLength    = 0x920a
	tagGpsLatRef      = 0x0001
	tagGpsLat         = 0x0002
	tagGpsLonRef      = 0x0003
	tagGpsLon         = 0x0004
	typeASCII         = 2
	typeShort         = 3
	typeLong          = 4
	typeRation        = 5
)

// tiffReader reads multi-byte integers from a TIFF structure in the byte
// order recorded by its byte-order mark.
type tiffReader struct {
	data   []byte
	little bool
}

func (t *tiffReader) u16(off int) uint16 {
	if t.little {
		return binary.LittleEndian.Uint16(t.data[off:])
	}
	return binary.BigEndian.Uint16(t.data[off:])
}

func (t *tiffReader) u32(off int) uint32 {
	if t.little {
		return binary.LittleEndian.Uint32(t.data[off:])
	}
	return binary.BigEndian.Uint32(t.data[off:])
}

// valueOffset reports where the entry's value lives: inline in the 4-byte
// value field when it fits, else at the recorded byte offset. It returns -1
// when out of bounds.
func valueOffset(t *tiffReader, entry int, typ uint16, count uint32) int {
	size := typeSizeOf(typ) * int64(count)
	var off int64
	if size <= 4 {
		off = int64(entry + 8)
	} else {
		off = int64(t.u32(entry + 8))
	}
	if off < 0 || off+size > int64(len(t.data)) {
		return -1
	}
	return int(off)
}

func readASCII(t *tiffReader, entry int, typ uint16, count uint32) *string {
	if typ != typeASCII || count < 1 {
		return nil
	}
	off := valueOffset(t, entry, typ, count)
	if off < 0 {
		return nil
	}
	s := strings.TrimSpace(strings.TrimRight(string(t.data[off:off+int(count)]), "\x00"))
	if s == "" {
		return nil
	}
	return &s
}

func readNumber(t *tiffReader, entry int, typ uint16, count uint32) *int {
	if count < 1 {
		return nil
	}
	off := valueOffset(t, entry, typ, count)
	if off < 0 {
		return nil
	}
	switch typ {
	case typeShort:
		v := int(t.u16(off))
		return &v
	case typeLong:
		v := int(t.u32(off))
		return &v
	}
	return nil
}

func readRationals(t *tiffReader, entry int, typ uint16, count uint32) []float64 {
	if typ != typeRation || count < 1 {
		return nil
	}
	off := valueOffset(t, entry, typ, count)
	if off < 0 {
		return nil
	}
	values := make([]float64, 0, count)
	for i := uint32(0); i < count; i++ {
		num := t.u32(off + int(i)*8)
		den := t.u32(off + int(i)*8 + 4)
		if den == 0 {
			values = append(values, 0)
		} else {
			values = append(values, float64(num)/float64(den))
		}
	}
	return values
}

func firstRational(values []float64) *float64 {
	if len(values) == 0 {
		return nil
	}
	return &values[0]
}

func parseTiff(tiffData []byte, meta *ExifMetadata) {
	if len(tiffData) < 8 {
		return
	}
	var little bool
	switch {
	case tiffData[0] == 0x49 && tiffData[1] == 0x49:
		little = true // "II"
	case tiffData[0] == 0x4d && tiffData[1] == 0x4d:
		little = false // "MM"
	default:
		return
	}
	t := &tiffReader{data: tiffData, little: little}
	if t.u16(2) != 42 {
		return
	}
	readIfd(t, int(t.u32(4)), meta)
}

func readIfd(t *tiffReader, offset int, meta *ExifMetadata) {
	if offset < 8 || offset+2 > len(t.data) {
		return
	}
	count := int(t.u16(offset))
	end := offset + 2 + count*12
	if end > len(t.data) {
		return
	}
	for i := 0; i < count; i++ {
		entry := offset + 2 + i*12
		tag := t.u16(entry)
		typ := t.u16(entry + 2)
		n := t.u32(entry + 4)
		switch tag {
		case tagImageWidth:
			if meta.ImageWidth == nil {
				meta.ImageWidth = readNumber(t, entry, typ, n)
			}
		case tagImageHeight:
			if meta.ImageHeight == nil {
				meta.ImageHeight = readNumber(t, entry, typ, n)
			}
		case tagMake:
			if meta.CameraMake == nil {
				meta.CameraMake = readASCII(t, entry, typ, n)
			}
		case tagModel:
			if meta.CameraModel == nil {
				meta.CameraModel = readASCII(t, entry, typ, n)
			}
		case tagOrientation:
			if meta.Orientation == nil {
				meta.Orientation = readNumber(t, entry, typ, n)
			}
		case tagSoftware:
			if meta.Software == nil {
				meta.Software = readASCII(t, entry, typ, n)
			}
		case tagDateTime:
			if meta.DateTime == nil {
				meta.DateTime = readASCII(t, entry, typ, n)
			}
		case tagExifIfdPointer:
			if sub := readNumber(t, entry, typeLong, 1); sub != nil {
				readExifIfd(t, *sub, meta)
			}
		case tagGpsIfdPointer:
			if gps := readNumber(t, entry, typeLong, 1); gps != nil {
				readGpsIfd(t, *gps, meta)
			}
		}
	}
}

func readExifIfd(t *tiffReader, offset int, meta *ExifMetadata) {
	if offset < 8 || offset+2 > len(t.data) {
		return
	}
	count := int(t.u16(offset))
	end := offset + 2 + count*12
	if end > len(t.data) {
		return
	}
	for i := 0; i < count; i++ {
		entry := offset + 2 + i*12
		tag := t.u16(entry)
		typ := t.u16(entry + 2)
		n := t.u32(entry + 4)
		switch tag {
		case tagExposureTime:
			if meta.ExposureTime == nil {
				meta.ExposureTime = firstRational(readRationals(t, entry, typ, n))
			}
		case tagFNumber:
			if meta.FNumber == nil {
				meta.FNumber = firstRational(readRationals(t, entry, typ, n))
			}
		case tagISO:
			if meta.ISO == nil {
				meta.ISO = readNumber(t, entry, typ, n)
			}
		case tagDateTimeOrig:
			// Phone photos usually carry the real capture time here only.
			if meta.DateTime == nil {
				meta.DateTime = readASCII(t, entry, typ, n)
			}
		case tagFocalLength:
			if meta.FocalLength == nil {
				meta.FocalLength = firstRational(readRationals(t, entry, typ, n))
			}
		}
	}
}

func readGpsIfd(t *tiffReader, offset int, meta *ExifMetadata) {
	if offset < 8 || offset+2 > len(t.data) {
		return
	}
	count := int(t.u16(offset))
	end := offset + 2 + count*12
	if end > len(t.data) {
		return
	}
	latRef, lonRef := "N", "E"
	var lat, lon []float64
	for i := 0; i < count; i++ {
		entry := offset + 2 + i*12
		tag := t.u16(entry)
		typ := t.u16(entry + 2)
		n := t.u32(entry + 4)
		switch tag {
		case tagGpsLatRef:
			if ref := readASCII(t, entry, typ, n); ref != nil {
				latRef = strings.ToUpper((*ref)[:1])
			}
		case tagGpsLat:
			lat = readRationals(t, entry, typ, n)
		case tagGpsLonRef:
			if ref := readASCII(t, entry, typ, n); ref != nil {
				lonRef = strings.ToUpper((*ref)[:1])
			}
		case tagGpsLon:
			lon = readRationals(t, entry, typ, n)
		}
	}
	if lat != nil && meta.GPSLatitude == nil {
		v := FormatGpsCoordinate(lat, latRef)
		meta.GPSLatitude = &v
	}
	if lon != nil && meta.GPSLongitude == nil {
		v := FormatGpsCoordinate(lon, lonRef)
		meta.GPSLongitude = &v
	}
}

// xmpToolRe extracts the editing software / creator tool from XMP XML, e.g.
// <xmp:CreatorTool>Pixelmator Pro</...>.
var xmpToolRe = regexp.MustCompile(`:(?:CreatorTool|Software)>([^<]+)<`)

func parseXmp(payload []byte, meta *ExifMetadata) {
	m := xmpToolRe.FindStringSubmatch(string(payload))
	if m != nil && meta.Software == nil {
		v := strings.TrimSpace(m[1])
		meta.Software = &v
	}
}

// --- JPEG parse -----------------------------------------------------------------

func parseJpeg(data []byte, meta *ExifMetadata) {
	for _, seg := range collectJpegSegments(data) {
		if seg.marker == 0xe1 {
			payload := data[seg.payloadStart:seg.end]
			if hasSignature(data, seg.payloadStart, exifSignature) {
				if len(payload) >= len(exifSignature) {
					parseTiff(payload[len(exifSignature):], meta)
				}
			} else {
				for _, sig := range xmpSignatures {
					if hasSignature(data, seg.payloadStart, sig) {
						parseXmp(payload, meta)
						break
					}
				}
			}
		} else if isSofMarker(seg.marker) && seg.end-seg.payloadStart >= 5 {
			// Start-of-frame header: precision(1), height(2), width(2), big-endian.
			if meta.ImageHeight == nil {
				v := int(binary.BigEndian.Uint16(data[seg.payloadStart+1:]))
				meta.ImageHeight = &v
			}
			if meta.ImageWidth == nil {
				v := int(binary.BigEndian.Uint16(data[seg.payloadStart+3:]))
				meta.ImageWidth = &v
			}
		}
	}
}

// --- PNG parse ------------------------------------------------------------------

func parsePng(data []byte, meta *ExifMetadata) {
	off := 8
	for off+8 <= len(data) {
		length := int(binary.BigEndian.Uint32(data[off:]))
		if length > len(data)-off-12 {
			break // corrupted chunk
		}
		typ := string(data[off+4 : off+8])
		chunk := data[off+8 : off+8+length]
		switch typ {
		case "IHDR":
			if off+16 <= len(data) {
				if meta.ImageWidth == nil {
					v := int(binary.BigEndian.Uint32(data[off+8:]))
					meta.ImageWidth = &v
				}
				if meta.ImageHeight == nil {
					v := int(binary.BigEndian.Uint32(data[off+12:]))
					meta.ImageHeight = &v
				}
			}
		case "tEXt", "iTXt":
			parsePngTextChunk(typ, chunk, meta)
		case "eXIf":
			parseTiff(chunk, meta)
		}
		if typ == "IEND" {
			break
		}
		off += 12 + length
	}
}

func parsePngTextChunk(kind string, data []byte, meta *ExifMetadata) {
	nul := bytes.IndexByte(data, 0)
	if nul < 1 {
		return
	}
	if string(data[:nul]) != "Software" {
		return
	}
	var text []byte
	if kind == "tEXt" {
		text = data[nul+1:]
	} else {
		// iTXt: keyword\0 compressionFlag(1) compressionMethod(1) languageTag\0
		// translatedKeyword\0 text(utf-8). Only uncompressed text is read.
		if nul+1 >= len(data) || data[nul+1] != 0 {
			return
		}
		if nul+3 > len(data) {
			return
		}
		p := nul + 3
		// Skip the language tag and the translated keyword (both NUL-terminated).
		for skipped := 0; skipped < 2; skipped++ {
			next := bytes.IndexByte(data[p:], 0)
			if next < 0 {
				return
			}
			p += next + 1
		}
		text = data[p:]
	}
	value := strings.TrimSpace(string(text))
	if value != "" && meta.Software == nil {
		meta.Software = &value
	}
}

// --- strip ------------------------------------------------------------------------

func concatParts(parts [][]byte) []byte {
	total := 0
	for _, p := range parts {
		total += len(p)
	}
	out := make([]byte, 0, total)
	for _, p := range parts {
		out = append(out, p...)
	}
	return out
}

func stripJpeg(data []byte) []byte {
	segments := collectJpegSegments(data)
	if segments == nil {
		return append([]byte(nil), data...) // corrupted walk - copy verbatim
	}
	parts := [][]byte{data[0:2]}
	for _, seg := range segments {
		if seg.marker == 0xda {
			// SOS header + entropy data + EOI are copied verbatim to the end.
			parts = append(parts, data[seg.start:])
			break
		}
		if isJpegMetadataSegment(data, seg) {
			continue
		}
		parts = append(parts, data[seg.start:seg.end])
	}
	return concatParts(parts)
}

func stripPng(data []byte) []byte {
	parts := [][]byte{data[0:8]}
	off := 8
	for off+8 <= len(data) {
		length := int(binary.BigEndian.Uint32(data[off:]))
		if length > len(data)-off-12 {
			break
		}
		typ := string(data[off+4 : off+8])
		// tEXt / iTXt / eXIf are the metadata carriers; everything else (IHDR,
		// PLTE, IDAT, ...) is copied byte-for-byte, CRC included.
		if typ != "tEXt" && typ != "iTXt" && typ != "eXIf" {
			parts = append(parts, data[off:off+12+length])
		}
		off += 12 + length
	}
	if off < len(data) {
		parts = append(parts, data[off:])
	}
	return concatParts(parts)
}

// --- public API ---------------------------------------------------------------------

// StripMetadata returns a rebuilt copy of buffer with every metadata segment
// removed. It is the Go twin of stripMetadata() in src/lib/exif-stripper.ts
// and must agree with it on every shared vector.
func StripMetadata(buffer []byte) ([]byte, error) {
	if len(buffer) < 8 {
		return nil, ErrTooSmall
	}
	if isJpeg(buffer) {
		return stripJpeg(buffer), nil
	}
	if isPng(buffer) {
		return stripPng(buffer), nil
	}
	return nil, ErrUnsupported
}

// ParseMetadata reads EXIF / XMP / IPTC metadata from a JPEG or PNG buffer and
// returns it together with a stripped copy. It is the Go twin of
// parseMetadata() in src/lib/exif-stripper.ts.
func ParseMetadata(buffer []byte) (ExifMetadata, error) {
	if len(buffer) < 8 {
		return ExifMetadata{}, ErrTooSmall
	}
	if !isJpeg(buffer) && !isPng(buffer) {
		return ExifMetadata{}, ErrUnsupported
	}
	stripped, err := StripMetadata(buffer)
	if err != nil {
		return ExifMetadata{}, err
	}
	meta := ExifMetadata{Stripped: stripped}
	if isJpeg(buffer) {
		parseJpeg(buffer, &meta)
	} else {
		parsePng(buffer, &meta)
	}
	return meta, nil
}

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 →