Skip to main content

ai_image_marker_stripper/
lib.rs

1// Copyright (c) 2026 Nikki James Pack
2// SPDX-License-Identifier: MIT
3
4//! Remove descriptive metadata and embedded AI provenance from PNG/APNG, JPEG
5//! and WebP images.
6//!
7//! [`strip`] works at the container level: it walks the chunks or segments of
8//! an image and keeps only those needed to render it, using an allowlist.
9//! Compressed image and frame data is copied unchanged and never re-encoded, so
10//! pixels are identical before and after. The optional [`watermarks`] module
11//! goes further and runs a local backend that alters pixels.
12//!
13//! See the README for exactly what is removed from each format and for known
14//! limitations.
15//!
16//! # Example
17//!
18//! ```no_run
19//! use ai_image_marker_stripper::{Options, strip};
20//!
21//! let input = std::fs::read("image.png")?;
22//! let cleaned = strip(&input, Options::default())?;
23//! println!("{} image; removed {:?}", cleaned.format, cleaned.removed);
24//! std::fs::write("image.cleaned.png", &cleaned.bytes)?;
25//! # Ok::<(), anyhow::Error>(())
26//! ```
27#![warn(missing_docs)]
28
29pub mod watermarks;
30
31mod process;
32
33use anyhow::{Context, Result, bail, ensure};
34use std::fmt;
35
36/// Options controlling what [`strip`] removes.
37///
38/// The default removes all descriptive metadata but keeps colour profiles.
39#[derive(Debug, Clone, Copy, Default)]
40pub struct Options {
41    /// Also remove ICC colour profiles (PNG `iCCP`, JPEG ICC APP2 segments and
42    /// WebP `ICCP`).
43    ///
44    /// Profiles can contain descriptive text, but removing them can change
45    /// how colours are displayed.
46    pub strip_color_profile: bool,
47}
48
49/// Image container format, detected from file contents rather than the file
50/// extension.
51///
52/// Displays as `PNG`, `JPEG` or `WebP`.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Format {
55    /// PNG, including animated PNG (APNG).
56    Png,
57    /// JPEG (JFIF or EXIF), baseline or progressive.
58    Jpeg,
59    /// WebP, lossy or lossless, still or animated.
60    WebP,
61}
62
63impl fmt::Display for Format {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.write_str(match self {
66            Self::Png => "PNG",
67            Self::Jpeg => "JPEG",
68            Self::WebP => "WebP",
69        })
70    }
71}
72
73/// The result of cleaning an image.
74#[derive(Debug)]
75pub struct Cleaned {
76    /// The complete cleaned image file, ready to be written to disk.
77    pub bytes: Vec<u8>,
78    /// The container format of [`bytes`](Self::bytes).
79    pub format: Format,
80    /// Names of the container blocks that were removed, in source order.
81    ///
82    /// Entries are chunk types (such as `tEXt` or `EXIF`), JPEG segment names
83    /// (such as `APP1` or `COM`), chunks inside WebP animation frames (prefixed
84    /// `ANMF/`), or `trailing data`. They describe containers, not whether the
85    /// image was AI-generated. An empty list means nothing needed removing.
86    pub removed: Vec<String>,
87}
88
89const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
90
91/// Remove metadata containers from a PNG, JPEG or WebP image.
92///
93/// The format is detected from the leading bytes of `input`. The returned
94/// image has the same format and decodes to identical pixels. Running `strip`
95/// on its own output removes nothing further.
96///
97/// No size limit is imposed and the output is held in memory, so callers
98/// handling untrusted input should bound its size first.
99///
100/// # Errors
101///
102/// Returns an error if the input is not PNG, JPEG or WebP, or if its container
103/// structure is malformed or truncated. Examples include a bad PNG CRC, an
104/// unknown critical PNG chunk, an invalid segment or chunk length, or a
105/// missing image. Nothing is partially returned on error.
106///
107/// # Example
108///
109/// ```no_run
110/// use ai_image_marker_stripper::{Options, strip};
111///
112/// let input = std::fs::read("photo.jpg")?;
113/// let options = Options { strip_color_profile: true };
114/// let cleaned = strip(&input, options)?;
115/// for block in &cleaned.removed {
116///     println!("removed {block}");
117/// }
118/// # Ok::<(), anyhow::Error>(())
119/// ```
120pub fn strip(input: &[u8], options: Options) -> Result<Cleaned> {
121    if input.starts_with(PNG_SIGNATURE) {
122        png(input, options)
123    } else if input.starts_with(b"\xff\xd8") {
124        jpeg(input, options)
125    } else if input.starts_with(b"RIFF") && input.get(8..12) == Some(b"WEBP") {
126        webp(input, options)
127    } else {
128        bail!("unsupported image: expected PNG, JPEG or WebP (detected by contents)")
129    }
130}
131
132fn be32(bytes: &[u8]) -> usize {
133    u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize
134}
135
136fn le32(bytes: &[u8]) -> usize {
137    u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize
138}
139
140fn label(bytes: &[u8]) -> String {
141    String::from_utf8_lossy(bytes).into_owned()
142}
143
144fn png(input: &[u8], options: Options) -> Result<Cleaned> {
145    let mut result = Cleaned {
146        bytes: PNG_SIGNATURE.to_vec(),
147        format: Format::Png,
148        removed: vec![],
149    };
150    let mut pos = PNG_SIGNATURE.len();
151    let mut seen_header = false;
152    let mut seen_image = false;
153    while pos < input.len() {
154        ensure!(input.len() - pos >= 12, "truncated PNG chunk at {pos}");
155        let len = be32(&input[pos..]);
156        ensure!(
157            len <= 0x7fff_ffff && len <= input.len() - pos - 12,
158            "invalid PNG chunk length at {pos}"
159        );
160        let end = pos + 12 + len;
161        let kind = &input[pos + 4..pos + 8];
162        ensure!(
163            kind.iter().all(u8::is_ascii_alphabetic) && kind[2].is_ascii_uppercase(),
164            "invalid PNG chunk type at {pos}"
165        );
166        let expected_crc = be32(&input[end - 4..end]) as u32;
167        ensure!(
168            crc32fast::hash(&input[pos + 4..end - 4]) == expected_crc,
169            "PNG CRC mismatch in {}",
170            label(kind)
171        );
172        if seen_header {
173            ensure!(kind != b"IHDR", "duplicate PNG IHDR");
174        } else {
175            ensure!(
176                kind == b"IHDR" && len == 13,
177                "PNG must start with a 13-byte IHDR"
178            );
179            seen_header = true;
180        }
181        // An allowlist removes private/unknown ancillary data as well as named metadata.
182        let keep = match kind {
183            b"IHDR" | b"PLTE" | b"IDAT" | b"IEND" | b"tRNS" | b"cHRM" | b"gAMA" | b"sRGB"
184            | b"sBIT" | b"bKGD" | b"cICP" | b"mDCV" | b"cLLI" | b"acTL" | b"fcTL" | b"fdAT" => true,
185            b"iCCP" => !options.strip_color_profile,
186            _ if kind[0].is_ascii_uppercase() => {
187                bail!("unknown critical PNG chunk {}", label(kind))
188            }
189            _ => false,
190        };
191        if keep {
192            result.bytes.extend_from_slice(&input[pos..end]);
193        } else {
194            result.removed.push(label(kind));
195        }
196        seen_image |= kind == b"IDAT";
197        pos = end;
198        if kind == b"IEND" {
199            ensure!(len == 0 && seen_image, "invalid PNG IEND or missing IDAT");
200            if pos < input.len() {
201                result.removed.push("trailing data".into());
202            }
203            return Ok(result);
204        }
205    }
206    bail!("PNG has no IEND")
207}
208
209fn is_restart_or_stuffing(code: u8) -> bool {
210    code == 0 || (0xd0..=0xd7).contains(&code)
211}
212
213/// Return the position of the first marker after entropy-coded scan data that
214/// is not byte stuffing (`FF00`) or a restart marker (`FFD0`–`FFD7`).
215fn jpeg_scan_end(input: &[u8], mut pos: usize) -> Result<usize> {
216    loop {
217        ensure!(pos < input.len(), "JPEG scan has no end marker");
218        if input[pos] != 0xff {
219            pos += 1;
220            continue;
221        }
222        let marker_start = pos;
223        while input.get(pos) == Some(&0xff) {
224            pos += 1;
225        }
226        let code = *input.get(pos).context("truncated JPEG scan marker")?;
227        if !is_restart_or_stuffing(code) {
228            return Ok(marker_start);
229        }
230        pos += 1;
231    }
232}
233
234fn jpeg(input: &[u8], options: Options) -> Result<Cleaned> {
235    let mut result = Cleaned {
236        bytes: input[..2].to_vec(),
237        format: Format::Jpeg,
238        removed: vec![],
239    };
240    let mut pos = 2;
241    let mut scanning = false;
242    let mut saw_scan = false;
243    loop {
244        if scanning {
245            let end = jpeg_scan_end(input, pos)?;
246            result.bytes.extend_from_slice(&input[pos..end]);
247            pos = end;
248            scanning = false;
249        }
250        let start = pos;
251        ensure!(
252            input.get(pos) == Some(&0xff),
253            "expected JPEG marker at {pos}"
254        );
255        while input.get(pos) == Some(&0xff) {
256            pos += 1;
257        }
258        let code = *input.get(pos).context("truncated JPEG marker")?;
259        pos += 1;
260        if code == 0xd9 {
261            ensure!(saw_scan, "JPEG has no image scan");
262            result.bytes.extend_from_slice(&input[start..pos]);
263            if pos < input.len() {
264                result.removed.push("trailing data".into());
265            }
266            return Ok(result);
267        }
268        ensure!(
269            code != 0xd8 && !is_restart_or_stuffing(code),
270            "unexpected JPEG marker FF{code:02X}"
271        );
272        // TEM is a standalone marker with no length field.
273        if code == 0x01 {
274            result.bytes.extend_from_slice(&input[start..pos]);
275            continue;
276        }
277        ensure!(input.len() - pos >= 2, "truncated JPEG segment length");
278        let len = usize::from(u16::from_be_bytes([input[pos], input[pos + 1]]));
279        ensure!(
280            len >= 2 && len <= input.len() - pos,
281            "invalid JPEG segment length"
282        );
283        let payload = &input[pos + 2..pos + len];
284        let end = pos + len;
285
286        // Keep only the fixed JFIF header, ICC profile segments and the fixed Adobe
287        // colour transform header. Drop JFIF thumbnails and every other APP segment.
288        let is_app = (0xe0..=0xef).contains(&code);
289        let is_comment = code == 0xfe;
290        let is_jfif = code == 0xe0 && payload.starts_with(b"JFIF\0") && payload.len() >= 14;
291        let is_icc = code == 0xe2 && payload.starts_with(b"ICC_PROFILE\0") && payload.len() >= 14;
292        let is_adobe = code == 0xee && payload.starts_with(b"Adobe") && payload.len() == 12;
293        if is_jfif {
294            // Rewrite as a bare 16-byte JFIF header with a zero-sized thumbnail.
295            result.bytes.extend_from_slice(b"\xff\xe0\x00\x10");
296            result.bytes.extend_from_slice(&payload[..12]);
297            result.bytes.extend_from_slice(&[0, 0]);
298            if payload.len() != 14 || payload[12..14] != [0, 0] {
299                result.removed.push("APP0 JFIF thumbnail/extra data".into());
300            }
301        } else if (!is_app && !is_comment) || (is_icc && !options.strip_color_profile) || is_adobe {
302            result.bytes.extend_from_slice(&input[start..end]);
303        } else if is_comment {
304            result.removed.push("COM".into());
305        } else {
306            result.removed.push(format!("APP{}", code - 0xe0));
307        }
308        pos = end;
309        match code {
310            0xda => {
311                scanning = true;
312                saw_scan = true;
313            }
314            // A DNL segment can interrupt a scan without starting a new one.
315            0xdc if saw_scan => scanning = true,
316            _ => {}
317        }
318    }
319}
320
321fn write_riff_chunk(out: &mut Vec<u8>, kind: &[u8], payload: &[u8]) -> Result<()> {
322    let size = u32::try_from(payload.len())?;
323    out.extend_from_slice(kind);
324    out.extend_from_slice(&size.to_le_bytes());
325    out.extend_from_slice(payload);
326    if size % 2 != 0 {
327        out.push(0);
328    }
329    Ok(())
330}
331
332/// Filter a sequence of RIFF chunks, either the top level of a WebP file or
333/// the chunks nested inside an animation frame (`in_frame`).
334fn webp_chunks(
335    input: &[u8],
336    in_frame: bool,
337    options: Options,
338    removed: &mut Vec<String>,
339) -> Result<Vec<u8>> {
340    let mut out = vec![];
341    let mut pos = 0;
342    let mut seen_image = false;
343    while pos < input.len() {
344        ensure!(input.len() - pos >= 8, "truncated WebP chunk");
345        let kind = &input[pos..pos + 4];
346        let len = le32(&input[pos + 4..]);
347        ensure!(len <= input.len() - pos - 8, "invalid WebP chunk length");
348        let end = pos + 8 + len;
349        let padding = len % 2;
350        ensure!(input.len() - end >= padding, "missing WebP chunk padding");
351        let payload = &input[pos + 8..end];
352        match kind {
353            b"VP8 " | b"VP8L" | b"ALPH" => {
354                seen_image |= kind != b"ALPH";
355                write_riff_chunk(&mut out, kind, payload)?;
356            }
357            b"VP8X" if !in_frame => {
358                ensure!(pos == 0 && len == 10, "invalid WebP VP8X header");
359                let mut header = payload.to_vec();
360                header[0] &= !0x0c; // EXIF and XMP flags
361                if options.strip_color_profile {
362                    header[0] &= !0x20; // ICC flag
363                }
364                write_riff_chunk(&mut out, kind, &header)?;
365            }
366            b"ICCP" if !in_frame && !options.strip_color_profile => {
367                write_riff_chunk(&mut out, kind, payload)?;
368            }
369            b"ANIM" if !in_frame => {
370                ensure!(len == 6, "invalid WebP ANIM header");
371                write_riff_chunk(&mut out, kind, payload)?;
372            }
373            b"ANMF" if !in_frame => {
374                ensure!(len >= 16, "truncated WebP frame header");
375                let mut frame = payload[..16].to_vec();
376                frame.extend(webp_chunks(&payload[16..], true, options, removed)?);
377                write_riff_chunk(&mut out, kind, &frame)?;
378                seen_image = true;
379            }
380            _ => removed.push(format!(
381                "{}{}",
382                if in_frame { "ANMF/" } else { "" },
383                label(kind)
384            )),
385        }
386        pos = end + padding;
387    }
388    ensure!(
389        seen_image,
390        "WebP {}contains no image data",
391        if in_frame { "frame " } else { "" }
392    );
393    Ok(out)
394}
395
396fn webp(input: &[u8], options: Options) -> Result<Cleaned> {
397    let size = le32(&input[4..]);
398    ensure!(
399        size >= 4 && size <= input.len() - 8,
400        "invalid WebP RIFF length"
401    );
402    let end = size + 8;
403    let mut removed = vec![];
404    let body = webp_chunks(&input[12..end], false, options, &mut removed)?;
405    if end < input.len() {
406        removed.push("trailing data".into());
407    }
408    let size = u32::try_from(body.len() + 4)?;
409    let mut bytes = b"RIFF".to_vec();
410    bytes.extend_from_slice(&size.to_le_bytes());
411    bytes.extend_from_slice(b"WEBP");
412    bytes.extend(body);
413    Ok(Cleaned {
414        bytes,
415        format: Format::WebP,
416        removed,
417    })
418}