EXIF & Metadata Stripper — Rust source
View and strip GPS, camera, date, and software metadata from photos entirely in your browser. Download a clean copy.
This is the Rust 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: Rust (std only — no external crates, not even `image`).
//! 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 `byteorder`-free
//! `u16`/`u32` reads, 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. `&[u8]` in, `Vec<u8>` out; every read is
//! bounds-checked so a corrupted file yields whatever parsed so far instead
//! of panicking.
//!
//! display source — part of CosmoDev's polyglot tool pages.
/// Everything the parser can surface, plus the rebuilt metadata-free image.
#[derive(Default)]
pub struct ExifMetadata {
pub camera_make: Option<String>,
pub camera_model: Option<String>,
pub software: Option<String>,
pub date_time: Option<String>,
/// Decimal degrees; negative for southern / western hemispheres.
pub gps_latitude: Option<f64>,
pub gps_longitude: Option<f64>,
pub image_width: Option<u32>,
pub image_height: Option<u32>,
/// EXIF orientation value 1-8.
pub orientation: Option<u16>,
/// Seconds (e.g. 0.004 = 1/250 s).
pub exposure_time: Option<f64>,
/// F-number (e.g. 2.8).
pub f_number: Option<f64>,
pub iso: Option<u16>,
/// Millimetres.
pub focal_length: Option<f64>,
/// A rebuilt copy of the input with every metadata segment removed.
pub stripped: Vec<u8>,
}
/// Degrees/minutes/seconds + hemisphere reference -> signed decimal degrees.
pub fn format_gps_coordinate(degrees: &[f64], reference: &str) -> f64 {
let get = |i: usize| degrees.get(i).copied().unwrap_or(0.0);
let decimal = get(0) + get(1) / 60.0 + get(2) / 3600.0;
if reference == "S" || reference == "W" { -decimal } else { decimal }
}
// --- format detection -------------------------------------------------------------
const PNG_SIGNATURE: [u8; 8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
const EXIF_SIGNATURE: &[u8] = b"Exif\0\0";
const IPTC_SIGNATURE: &[u8] = b"Photoshop 3.0\0";
const XMP_SIGNATURES: [&[u8]; 2] =
[b"http://ns.adobe.com/xap/1.0/", b"http://ns.adobe.com/xmp/extension/"];
fn is_jpeg(b: &[u8]) -> bool { b.len() >= 2 && b[0] == 0xFF && b[1] == 0xD8 }
fn is_png(b: &[u8]) -> bool { b.len() >= 8 && b[..8] == PNG_SIGNATURE }
fn has_signature(b: &[u8], off: usize, sig: &[u8]) -> bool {
off.checked_add(sig.len()).is_some_and(|end| end <= b.len()) && &b[off..off + sig.len()] == sig
}
// --- TIFF / EXIF IFD parsing -------------------------------------------------------
/// EXIF field type -> byte size per component.
const fn type_size(t: u16) -> usize {
match t { 5 | 10 => 8, 3 => 2, 4 | 9 => 4, _ => 1 }
}
const TAG_IMAGE_WIDTH: u16 = 0x0100;
const TAG_IMAGE_HEIGHT: u16 = 0x0101;
const TAG_ORIENTATION: u16 = 0x0112;
const TAG_MAKE: u16 = 0x010F;
const TAG_MODEL: u16 = 0x0110;
const TAG_SOFTWARE: u16 = 0x0131;
const TAG_DATE_TIME: u16 = 0x0132;
const TAG_EXIF_IFD_POINTER: u16 = 0x8769;
const TAG_GPS_IFD_POINTER: u16 = 0x8825;
const TAG_EXPOSURE_TIME: u16 = 0x829A;
const TAG_F_NUMBER: u16 = 0x829D;
const TAG_ISO: u16 = 0x8827;
const TAG_DATE_TIME_ORIGINAL: u16 = 0x9003;
const TAG_FOCAL_LENGTH: u16 = 0x920A;
const TAG_GPS_LAT_REF: u16 = 0x0001;
const TAG_GPS_LAT: u16 = 0x0002;
const TAG_GPS_LON_REF: u16 = 0x0003;
const TAG_GPS_LON: u16 = 0x0004;
const TYPE_ASCII: u16 = 2;
const TYPE_SHORT: u16 = 3;
const TYPE_LONG: u16 = 4;
const TYPE_RATIONAL: u16 = 5;
/// A TIFF block plus the byte order taken from its BOM ("II"/"MM").
struct Tiff<'a> { b: &'a [u8], little: bool }
impl Tiff<'_> {
fn u16(&self, off: usize) -> Option<u16> {
let s = self.b.get(off..off + 2)?;
Some(if self.little { u16::from_le_bytes(s.try_into().unwrap()) }
else { u16::from_be_bytes(s.try_into().unwrap()) })
}
fn u32(&self, off: usize) -> Option<u32> {
let s = self.b.get(off..off + 4)?;
Some(if self.little { u32::from_le_bytes(s.try_into().unwrap()) }
else { u32::from_be_bytes(s.try_into().unwrap()) })
}
/// Where the entry's value lives: inline in the 4-byte field when it fits,
/// else at the recorded offset. None when out of bounds.
fn value_offset(&self, entry: usize, ftype: u16, count: u32) -> Option<usize> {
let size = type_size(ftype) * count as usize;
let off = if size <= 4 { entry + 8 } else { self.u32(entry + 8)? as usize };
off.checked_add(size).filter(|&end| end <= self.b.len()).map(|_| off)
}
fn ascii(&self, entry: usize, ftype: u16, count: u32) -> Option<String> {
if ftype != TYPE_ASCII || count < 1 { return None; }
let off = self.value_offset(entry, ftype, count)?;
let raw = &self.b[off..off + count as usize];
let text = String::from_utf8_lossy(raw);
let trimmed = text.trim_end_matches('\0').trim();
if trimmed.is_empty() { None } else { Some(trimmed.to_string()) }
}
fn number(&self, entry: usize, ftype: u16, count: u32) -> Option<u32> {
if count < 1 { return None; }
let off = self.value_offset(entry, ftype, count)?;
match ftype { TYPE_SHORT => self.u16(off).map(|v| v as u32), TYPE_LONG => self.u32(off), _ => None }
}
fn rationals(&self, entry: usize, ftype: u16, count: u32) -> Option<Vec<f64>> {
if ftype != TYPE_RATIONAL || count < 1 { return None; }
let off = self.value_offset(entry, ftype, count)?;
(0..count as usize)
.map(|i| {
let num = self.u32(off + i * 8)? as f64;
let den = self.u32(off + i * 8 + 4)? as f64;
Some(if den == 0.0 { 0.0 } else { num / den })
})
.collect()
}
}
fn set<T>(slot: &mut Option<T>, value: Option<T>) {
if slot.is_none() { *slot = value; }
}
fn read_ifd(t: &Tiff, offset: usize, meta: &mut ExifMetadata) {
let Some(count) = t.u16(offset).filter(|_| offset >= 8) else { return };
if offset + 2 + count as usize * 12 > t.b.len() { return; }
for i in 0..count as usize {
let entry = offset + 2 + i * 12;
let (Some(tag), Some(ftype), Some(n)) = (t.u16(entry), t.u16(entry + 2), t.u32(entry + 4)) else { continue };
match tag {
TAG_MAKE => set(&mut meta.camera_make, t.ascii(entry, ftype, n)),
TAG_MODEL => set(&mut meta.camera_model, t.ascii(entry, ftype, n)),
TAG_SOFTWARE => set(&mut meta.software, t.ascii(entry, ftype, n)),
TAG_DATE_TIME | TAG_DATE_TIME_ORIGINAL => set(&mut meta.date_time, t.ascii(entry, ftype, n)),
TAG_IMAGE_WIDTH => set(&mut meta.image_width, t.number(entry, ftype, n)),
TAG_IMAGE_HEIGHT => set(&mut meta.image_height, t.number(entry, ftype, n)),
TAG_ORIENTATION => set(&mut meta.orientation, t.number(entry, ftype, n).map(|v| v as u16)),
TAG_ISO => set(&mut meta.iso, t.number(entry, ftype, n).map(|v| v as u16)),
TAG_EXPOSURE_TIME => set(&mut meta.exposure_time, t.rationals(entry, ftype, n).and_then(|v| v.into_iter().next())),
TAG_F_NUMBER => set(&mut meta.f_number, t.rationals(entry, ftype, n).and_then(|v| v.into_iter().next())),
TAG_FOCAL_LENGTH => set(&mut meta.focal_length, t.rationals(entry, ftype, n).and_then(|v| v.into_iter().next())),
TAG_EXIF_IFD_POINTER => if let Some(sub) = t.number(entry, TYPE_LONG, 1) { read_ifd(t, sub as usize, meta) },
TAG_GPS_IFD_POINTER => if let Some(gps) = t.number(entry, TYPE_LONG, 1) { read_gps_ifd(t, gps as usize, meta) },
_ => {}
}
}
}
fn read_gps_ifd(t: &Tiff, offset: usize, meta: &mut ExifMetadata) {
let Some(count) = t.u16(offset).filter(|_| offset >= 8) else { return };
if offset + 2 + count as usize * 12 > t.b.len() { return; }
let (mut lat_ref, mut lon_ref) = ("N".to_string(), "E".to_string());
let mut lat = None;
let mut lon = None;
for i in 0..count as usize {
let entry = offset + 2 + i * 12;
let (Some(tag), Some(ftype), Some(n)) = (t.u16(entry), t.u16(entry + 2), t.u32(entry + 4)) else { continue };
match tag {
TAG_GPS_LAT_REF => if let Some(r) = t.ascii(entry, ftype, n) { lat_ref = r } ,
TAG_GPS_LON_REF => if let Some(r) = t.ascii(entry, ftype, n) { lon_ref = r },
TAG_GPS_LAT => lat = t.rationals(entry, ftype, n),
TAG_GPS_LON => lon = t.rationals(entry, ftype, n),
_ => {}
}
}
let upper = |r: &str| r.chars().next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_else(|| "N".to_string());
if lat.is_some() { set(&mut meta.gps_latitude, lat.map(|v| format_gps_coordinate(&v, &upper(&lat_ref)))); }
if lon.is_some() { set(&mut meta.gps_longitude, lon.map(|v| format_gps_coordinate(&v, &upper(&lon_ref)))); }
}
fn parse_tiff(tiff_bytes: &[u8], meta: &mut ExifMetadata) {
if tiff_bytes.len() < 8 { return; }
let little = match tiff_bytes[..2] { [0x49, 0x49] => true, [0x4D, 0x4D] => false, _ => return };
let t = Tiff { b: tiff_bytes, little };
if t.u16(2) != Some(42) { return; }
if let Some(first) = t.u32(4) { read_ifd(&t, first as usize, meta); }
}
/// XMP is XML; the only field surfaced is the creator tool / software.
fn parse_xmp(payload: &[u8], meta: &mut ExifMetadata) {
let text = String::from_utf8_lossy(payload);
for open in ["<xmp:CreatorTool>", "<xmp:Software>"] {
if let Some(start) = text.find(open) {
let rest = &text[start + open.len()..];
if let Some(end) = rest.find('<') {
let value = rest[..end].trim();
if !value.is_empty() { set(&mut meta.software, Some(value.to_string())); }
return;
}
}
}
}
// --- JPEG / PNG parse ---------------------------------------------------------------
/// One length-prefixed JPEG marker segment: (marker, start, end, payload start).
type Segment = (u8, usize, usize, usize);
/// Walks markers from just after the SOI up to SOS/EOI; None when corrupted.
fn collect_jpeg_segments(b: &[u8]) -> Option<Vec<Segment>> {
let mut segments = Vec::new();
let mut off = 2;
while off + 2 <= b.len() {
if b[off] != 0xFF { return None; }
if b[off + 1] == 0xFF { off += 1; continue; } // padding fill byte
let marker = b[off + 1];
if marker == 0x01 || (0xD0..=0xD9).contains(&marker) { // standalone markers
segments.push((marker, off, off + 2, off + 2));
if marker == 0xD9 { break; }
off += 2;
continue;
}
if off + 4 > b.len() { return None; }
let size = u16::from_be_bytes(b[off + 2..off + 4].try_into().unwrap()) as usize;
if size < 2 || off + 2 + size > b.len() { return None; }
segments.push((marker, off, off + 2 + size, off + 4));
if marker == 0xDA { break; } // SOS - entropy data follows
off += 2 + size;
}
Some(segments)
}
fn is_jpeg_metadata_segment(b: &[u8], seg: Segment) -> bool {
let (marker, _, _, payload) = seg;
marker == 0xE1 && (has_signature(b, payload, EXIF_SIGNATURE)
|| XMP_SIGNATURES.iter().any(|sig| has_signature(b, payload, sig)))
|| marker == 0xED && has_signature(b, payload, IPTC_SIGNATURE)
}
fn parse_jpeg(b: &[u8], meta: &mut ExifMetadata) {
for seg in collect_jpeg_segments(b).unwrap_or_default() {
let (marker, _start, end, payload) = seg;
if marker == 0xE1 {
let chunk = &b[payload..end];
if has_signature(b, payload, EXIF_SIGNATURE) {
parse_tiff(&chunk[EXIF_SIGNATURE.len()..], meta);
} else if XMP_SIGNATURES.iter().any(|sig| has_signature(b, payload, sig)) {
parse_xmp(chunk, meta);
}
} else if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC)
&& end - payload >= 5
{
// Start-of-frame header: precision(1), height(2), width(2), big-endian.
set(&mut meta.image_height, Some(u16::from_be_bytes(b[payload + 1..payload + 3].try_into().unwrap()) as u32));
set(&mut meta.image_width, Some(u16::from_be_bytes(b[payload + 3..payload + 5].try_into().unwrap()) as u32));
}
}
}
/// Visits every PNG chunk; returns the offset where the walk stopped.
fn each_png_chunk(b: &[u8], mut visit: impl FnMut(&str, &[u8], usize, usize)) -> usize {
let mut off = 8;
while off + 8 <= b.len() {
let length = u32::from_be_bytes(b[off..off + 4].try_into().unwrap()) as usize;
if length > b.len().saturating_sub(off + 12) { break; } // corrupted chunk
let ctype = String::from_utf8_lossy(&b[off + 4..off + 8]).into_owned();
visit(&ctype, &b[off + 8..off + 8 + length], off, length);
if ctype == "IEND" { off += 12 + length; break; }
off += 12 + length;
}
off
}
fn parse_png(b: &[u8], meta: &mut ExifMetadata) {
each_png_chunk(b, |ctype, data, off, _| match ctype {
"IHDR" => {
set(&mut meta.image_width, Some(u32::from_be_bytes(data[0..4].try_into().unwrap())));
set(&mut meta.image_height, Some(u32::from_be_bytes(data[4..8].try_into().unwrap())));
}
"tEXt" | "iTXt" => parse_png_text_chunk(ctype, data, meta),
"eXIf" => parse_tiff(data, meta),
_ => { let _ = off; }
});
}
fn parse_png_text_chunk(kind: &str, data: &[u8], meta: &mut ExifMetadata) {
let Some(nul) = data.iter().position(|&c| c == 0) else { return };
if nul < 1 || &data[..nul] != b"Software" { return; }
let text: &[u8] = if kind == "tEXt" {
&data[nul + 1..]
} else {
// iTXt: keyword\0 compressionFlag(1) method(1) langTag\0 translated\0 text.
if data.get(nul + 1) != Some(&0) { return; } // compressed - not read
let mut pos = nul + 3;
for _ in 0..2 { // skip the language tag and the translated keyword
let Some(next) = data[pos..].iter().position(|&c| c == 0) else { return };
pos += next + 1;
}
&data[pos..]
};
let value = String::from_utf8_lossy(text).trim().to_string();
if !value.is_empty() { set(&mut meta.software, Some(value)); }
}
// --- strip ---------------------------------------------------------------------------
fn strip_jpeg(b: &[u8]) -> Vec<u8> {
let Some(segments) = collect_jpeg_segments(b) else { return b.to_vec() }; // corrupted walk
let mut parts: Vec<&[u8]> = vec![&b[..2]];
for (marker, start, end, payload) in segments {
if marker == 0xDA {
parts.push(&b[start..]); // SOS header + entropy data + EOI, verbatim
break;
}
if !is_jpeg_metadata_segment(b, (marker, start, end, payload)) {
parts.push(&b[start..end]);
}
}
parts.concat()
}
fn strip_png(b: &[u8]) -> Vec<u8> {
let mut parts: Vec<&[u8]> = vec![&b[..8]];
let end = each_png_chunk(b, |ctype, _, off, length| {
// tEXt / iTXt / eXIf are the metadata carriers; every other chunk
// (IHDR, PLTE, IDAT, ...) is copied byte-for-byte, CRC included.
if !matches!(ctype, "tEXt" | "iTXt" | "eXIf") {
parts.push(&b[off..off + 12 + length]);
}
});
if end < b.len() { parts.push(&b[end..]); }
parts.concat()
}
// --- public API ----------------------------------------------------------------------
/// Rebuild the image without any metadata segment; lossless for JPEG.
///
/// # Errors
/// Errors when the buffer is too small to be an image or is neither JPEG nor PNG.
pub fn strip_metadata(buffer: &[u8]) -> Result<Vec<u8>, String> {
if buffer.len() < 8 { return Err("File is too small to be a valid image.".into()); }
if is_jpeg(buffer) { return Ok(strip_jpeg(buffer)); }
if is_png(buffer) { return Ok(strip_png(buffer)); }
Err("Unsupported format: only JPEG and PNG images are supported.".into())
}
/// Read every supported metadata field, plus a stripped copy of the image.
///
/// # Errors
/// Errors when the buffer is too small to be an image or is neither JPEG nor PNG.
pub fn parse_metadata(buffer: &[u8]) -> Result<ExifMetadata, String> {
if buffer.len() < 8 { return Err("File is too small to be a valid image.".into()); }
if !is_jpeg(buffer) && !is_png(buffer) {
return Err("Unsupported format: only JPEG and PNG images are supported.".into());
}
let mut meta = ExifMetadata { stripped: strip_metadata(buffer)?, ..Default::default() };
if is_jpeg(buffer) { parse_jpeg(buffer, &mut meta); } else { parse_png(buffer, &mut meta); }
Ok(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 →