diff --git a/CHANGELOG.md b/CHANGELOG.md
index e87ec8eb..b589eaf2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -67,6 +67,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- AVI INFO text honours a `CSET` chunk (code page 65001, 1252, 0 or 28591); without one, valid UTF-8 (ffmpeg's and TagLib#'s encoding) is read as UTF-8 and other text as Windows-1252. On save, an unchanged value keeps its exact bytes and the file keeps its `CSET` (or its absence); changed values are written in the file's code page when they fit it (ASCII only when there is no `CSET`), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it. When the list becomes UTF-8, untouched text in a declared code page decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; a save that would have to rewrite untouched text whose code page is a guess (no `CSET`), is not decoded here (for example Shift-JIS or cp1251), or that holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0) is refused, and the error names the field and which of those reasons applies. A CSET rewritten to 65001 keeps the file's country, language and dialect codes. The five undefined 1252 code points are never written as 1252 bytes; a value holding one goes to UTF-8. WAV INFO is unchanged (Latin-1).
- A path save copies `movi` in 64 KB pieces and patches `idx1` and OpenDML indexes from the source, so it no longer loads the file. `Render` and `SaveToFile(path, span)` still build one buffer. `MediaFile.Read` and `AviFile.ReadFromFile` read only the header and tag chunks.
- Matroska `AlbumArtistSort` and `ComposerSort`: `SORT_WITH` nested in the album-level `ARTIST` (`TargetTypeValue` 50) and in `COMPOSER`, with flat `ALBUM_ARTIST_SORT` / `COMPOSER_SORT` as the fallback. Clearing removes both forms at every level the getter reads. When the track inherits the album's `ARTIST`, writing either `ArtistSort` or `AlbumArtistSort` first copies that `ARTIST` to the track level, so the other sort is kept (#116).
+- Still images: `MediaFile.Read` and `StillImageFile.Read`/`ReadFromFile`/`ReadFromFileAsync` open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height. A TIFF or DNG reports the size exiftool's ImageSize gives (measured case by case): the width and height of the first IFD whose NewSubfileType is 0, the full-resolution image, in the order exiftool reads them (IFD0, its SubIFDs depth first with their next IFDs, then IFD0's next IFD), or else IFD0's; unlike exiftool, a width and a height come from one IFD, and a size of 0, a negative one or one past 2^31 - 1 is none. DNG is TIFF with the DNG version tag in IFD0. A table of any size whose entries fit in the data is read, as exiftool reads one of 65,535 entries, and SubIFD offsets are decoded as exiftool decodes them, with the same rules as the Exif pointers below (in BigTIFF also LONG8, SLONG8 and IFD8, but not UNDEFINED); the walk reads at most 4,096 IFDs, 64 SubIFD levels deep, and stops once it has read more entries than tables that do not overlap could hold. A classic IFD is read when 0, 2 or 4 bytes of its next-IFD field are present and is not read when 1 or 3 are (exiftool 13.55 drops that directory). When that directory is IFD0 the file is not opened, and the error is "IFD0's next-IFD field has 1 of its 4 bytes, so IFD0 is not read and the image has no size" (or 3 of its 4 bytes). A wholly missing next field is still read, with no next IFD. A JPEG whose frame height is 0 takes it from the DNL segment after the first scan (ITU-T T.81 §B.2.5). PNG text keywords (Title, Author, Description, Copyright, Creation Time, Comment) are written before the pixel data, the GIF comment after the header, and the JPEG COM marker before the scan; exiftool's PNG `Artist` keyword is read as the artist when there is no `Author`. `Render` copies every other byte, including the pixels and anything after the PNG IEND, the GIF trailer, or the JPEG EOI; a no-op save is byte-identical. A path save (`SaveToFile(path)` and `SaveToFileAsync`) copies those pixels in 64 KB pieces and writes the same bytes as `Render`. When a field changes, its copies elsewhere in the file change too: the XMP property (`dc:title`, `dc:creator`, `dc:description`, `dc:rights`, `exif:UserComment`) is replaced in place, keeping its start and end tags, or removed for null, in PNG `XML:com.adobe.xmp` and ImageMagick's `Raw profile type xmp`, JPEG APP1 XMP, and the GIF XMP extension; the Exif copies (IFD0 `ImageDescription`, `Artist`, `Copyright`, the Windows XP title, author and comment tags, and `UserComment`) are removed from PNG `eXIf`, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags (measured with exiftool 13.55): IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD (0xA005) any of them points at, however deep (exiftool shows a copy from any of them; ImageIO and TagLib# read a subset), each table walked once. A pointer is followed as exiftool decodes it: a BYTE, SHORT, LONG, SBYTE, SSHORT, SLONG or IFD value, or UNDEFINED with count 1; an Exif IFD pointer only with count 1, a GPS or interoperability pointer by its first value, SubIFDs by every value; a negative value, or values that do not all lie in the data, name nothing; two pointer arrays at one offset are each read by their own type. IFD0's Exif IFD and GPS pointers are also followed as TagLib# reads them, their 4-byte field taken as a LONG whatever their type and count (measured), so the copy TagLib# shows from such a table is removed too, and its GPS table is protected. A GPS table is read with its GPS tags only: nothing in it is edited and no pointer in it is followed. A table is walked when its entries fit in the data. A pointer whose table's entries do not fit is skipped, as readers skip it. A field edit runs only when that structure is plain, and nothing is written otherwise. It is not plain when a strip, tile or thumbnail offset or length (TIFF 6.0 tags 0x0111/0x0117, 0x0144/0x0145 and 0x0201/0x0202) is typed other than SHORT or LONG; when one of those arrays is named more than once (two tables, both sides of one pair, or the same tag twice in one table); when a complete pair names more values than half the bytes; when a classic next-IFD field has only one, two or three of its four bytes (a wholly absent next field stays editable; exiftool itself still reads a table that has two); when removing an entry would change whether exiftool reads that table's first entry, including a change no tag shows; or when a removed value shares a protected byte, or compacting a table would rewrite any protected range other than that table. Two protected ranges may share a byte. Clear does not use this gate. An edit with nothing to remove still saves. A save is also refused when the tables hold more entries than the data could without overlapping and the block's bytes could hold an entry with one of the field's tags, of any type; edits with nothing to remove save. The `Artist` and ImageMagick `exif:*` text keywords are dropped. A packet no XMP reader reads because it is not well-formed, and does not name a changed field, an ImageMagick raw profile that is not hex, and PNG text that is not zlib data or whose iTXt header is cut short, which no reader decodes, are kept as they are; compressed text past the shared inflation budget is refused, since it cannot be checked. For a JPEG or GIF only the comment is stored, so only the comment's copies change. An XMP packet followed by NULs or padding (as ImageIO writes it) is edited and the tail kept, and GIF XMP written as data sub-blocks (ImageIO) is edited as well as the raw form with its magic trailer. A save that cannot update a copy (XMP that is not well-formed or has a DTD and names a changed field's property, a value XML cannot hold, an Exif block that is not classic TIFF and whose bytes could hold an entry with one of the field's tags, in either byte order, a JPEG XMP packet that would outgrow its segment, extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment) is refused with its own reason, as is a container that cannot be spliced, or a multi-picture JPEG whose MPF index cannot be corrected or (for Clear) followed; the file is left unchanged. A length-changing edit moves bytes after the edited segment, as exiftool does; a maker-note pointer to data after the image (for example Sony's preview tag 0x2001) is not rewritten (#163). When a maker note is not fully located, a removed value outside the Exif tables keeps its bytes. Inflated PNG text is capped at 1 MiB for the whole file, on read and on save. `Clear` removes all tag metadata and keeps only what a decoder or colour management needs, or the file's structure: PNG critical chunks and tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL and sTER; JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and the ISO 21496-1 gain map, APP14 Adobe, the XMP an HDR decoder needs to find and apply a gain map (Ultra HDR `hdrgm` and `Container`/`Item` directory, Apple `apdi` and `HDRGainMap` version and headroom, and the motion-photo `Camera:MotionPhoto`, `MotionPhotoVersion` and `MotionPhotoPresentationTimestampUs` so a motion photo stays one; Clear writes a new packet from those properties alone, each checked against the value the format defines (a version, a Boolean, a Real or three, an integer, a timestamp that may be -1, an item semantic of `Primary`, `GainMap` or `MotionPhoto`, a MIME type of `image/jpeg`, `image/heic`, `image/avif`, `video/mp4` or `video/quicktime`, a length or padding), so no other property, attribute, nested structure or text survives; an item value outside those lists is dropped and the item keeps its place and length, a directory item may be written as `rdf:li` > `rdf:Description`, and a directory with an entry that holds no item is dropped whole; the first occurrence of a property wins, and the gain map's `Item:Length` follows its new length while later items such as a motion-photo video keep theirs. An Apple gain map of version 65536 (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary image's Apple maker note, tags 33 and 48. For such a file Clear writes a new Exif in the primary holding only those two maker-note values, copied as stored, and nothing else of the Exif: no IFD0, GPS or other Exif tag and no other maker-note tag. The values kept are the ones ImageIO applies, measured with every level duplicated and broken (where libultrahdr reads a file differently, Clear follows ImageIO): the first Exif segment, whose TIFF magic must be 42; at each level (IFD0's Exif IFD pointers, each Exif IFD's MakerNote entries, the maker note's 0x0021 and 0x0030 entries) an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one, two Exif IFDs merging value by value; a maker-note value is usable when it is SRATIONAL with every value inside the maker note, at any offset; the headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image), and a winning MakerNote that is not Apple's keeps nothing. ImageIO then renders exactly what it rendered before, HDR or SDR; without the values it renders the photo SDR and libultrahdr refuses it. The new Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions, YCbCrPositioning, the resolution tags), consistent with Clear removing all other Exif, so `exiftool -validate` warns about them; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it), and the APP11 JPEG XT decoding boxes (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); GIF graphic control and plain text extensions, looping and ICC application extensions. Everything else goes, including PNG text, `eXIf`, `tIME` and `caBX`, JPEG Exif (but for the Apple headroom above), the rest of XMP and extended XMP, IPTC, maker segments and every other APP11 box (JUMBF/C2PA, `xml `, `uuid`, `json`, `Exif`, unknown), and GIF XMP and ImageMagick's IPTC. In a multi-picture JPEG (MPF), Clear cleans every image the MPF index lists with the same rules; the index's offsets and sizes are rewritten after Clear and after an edit. An MP index outside its APP2 segment, or listing an image before the first image's end (its EOI), outside the file or overlapping another, is not followed: Clear is refused, and so is an edit that would move the later images. Apple's PNG `iDOT` is dropped when a chunk between it and the first IDAT changes. A field the format does not store reads back as null. EXIF, IPTC, and XMP values are not read yet, and SVG metadata is not read or written yet.
#### Raw AAC (ADTS/ADIF) Support
- `AacFile` reads and writes raw AAC files (`.aac`): ADTS (ISO/IEC 13818-7 §6.2, MPEG-2 and MPEG-4) and ADIF (§6.1)
@@ -77,6 +78,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
+- An Exif field edit (Comment, Description, Copyright and the other stored fields) runs only when the Exif structure is plain. Otherwise it is refused, with the reason, and nothing is written. Clear is unchanged. A removed value that shares a protected byte, or a compaction that would rewrite any protected range other than the table itself, is refused. A strip, tile or thumbnail offset or length that is not SHORT or LONG, an array of those that does not lie wholly in the data, an array of those named more than once, a pair tag given twice in one table, a complete pair that names more values than half the bytes, a classic next-IFD field with one, two or three of its four bytes, or a first entry whose format would change whether exiftool reads the table, each refuse on their own. A wholly absent next field stays editable. A first-entry change that shows nothing new is still refused.
+- A path save copies still-image pixels in a rented 64 KB buffer and writes the same bytes as `Render`. `SaveToFile(path)` and `SaveToFileAsync` do this for JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG. `Render` still copies every other byte.
- A path save copies the audio in a rented 64 KB buffer and writes the same bytes as `Render` (#20). `SaveToFile(path)` and `SaveToFileAsync` do this for Ogg Vorbis, Opus, and Ogg FLAC, MP3, native FLAC, ASF/WMA, raw AAC, MPEG program streams, Audible, Monkey's Audio, WavPack, Musepack, DSF (when the samples were left on disk), MP4 including a chapter edit, WAV, AIFF, AVI, Matroska, and DFF. `SaveToFile(path, span)`, `Render`, and `ReadFromFile` still build one buffer. The source is closed when the destination is never created. A render failure is returned before an already-cancelled token.
- Matroska: `TotalTracks` and `TotalDiscs` follow the tagging spec. `TOTAL_PARTS` counts the parts of the first lower level ([tagging](https://www.matroska.org/technical/tagging.html)), so at 50 it is the album's track count and at 60 the set's disc count ([audio examples](https://www.matroska.org/technical/tagging-audio-example.html), "Collection of CD sets"). `Track` is `PART_NUMBER` at 30 and `DiscNumber` is `PART_NUMBER` at 50. ffmpeg's untargeted `PART_NUMBER` (read as the track), its `4/12` and `DISC=2/3` slash forms and its `TRACKTOTAL`/`DISCTOTAL` names are read as fallbacks; setting a total writes `TOTAL_PARTS` and removes them. A `TOTAL_PARTS` at 30 is read as the track total only when nothing else gives one, and is never written.
- Matroska: TagLib writes the track total at 30 and the disc total at 50, against the spec. A TagLib-written file holding both totals now reads its disc total as `TotalTracks`, and TagLib reads a stored level 50 `TOTAL_PARTS` written here as its disc total, reads an untargeted one (what this library writes on ffmpeg files) as its track total, and does not read 60. This is a deliberate spec choice.
@@ -97,6 +100,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- A path save that is cancelled while it writes the temp file no longer leaves that temp file beside the destination; the save fails with "Operation was cancelled" and the destination is left as it was.
- MP4 `Genre` reads the legacy `gnre` atom (a 1-based ID3v1 code: 25 is Soundtrack, 99 Easy Listening, 74 Acid Punk) when `©gen` is empty (#123). Setting `Genre` writes `©gen` and removes `gnre`.
- MP4 setters remove every atom their getter reads, so readers that show all of them (ffprobe joins them with `;`) show only the new value. Aliases read as a fallback and removed on set: `gnre` (Genre), `©cpy` (Copyright), `©com` (Composer) and `©swr` (EncoderSettings) from QuickTime user data, `titl`, `albm` and `dscp` (Title, Album, Description) as ExifTool reads them inside `ilst`, and `©st3` (Subtitle). `©aut`, `©inf`, `©des` and `grup` are not aliases and are kept. 3GPP's own `titl`/`albm`/`dscp` FullBoxes directly under `udta` are not read.
- MP4 saves keep `ilst` children the library does not map (for example `orch`, `©ope`, `©url`, `stik`, `purd` and the iTunes Store ids), a malformed cover or freeform atom, and freeform names that contain `:` (such as the CDDB `UFID…` atom of iTunes rips). Before, a save dropped them, even with no edit. The meta's other children (`hdlr`, `keys`, `free` padding) are written back as their original bytes.
diff --git a/README.md b/README.md
index 22492f46..9a80433e 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,7 @@ See the [Migration Guide](docs/MIGRATION-FROM-TAGLIB.md) for detailed comparison
- MPEG program streams (`.mpg`, `.mpeg`, `.mpe`, `.vob`) and MPEG video elementary streams (`.mpv`, `.m1v`, `.m2v`): duration, MPEG-1/MPEG-2 video properties, and the first audio stream (MPEG audio, AC-3, LPCM). ID3v2 in front of the stream, an ID3v2.4 tag appended after it (the layout TagLib# writes), and ID3v1 are read and written in place; the stream bytes are not changed.
- Audible `.aa`: the text dictionary (title, author, narrator, dates, descriptions, and every other key by name), the cover image, and the duration. Dictionary edits can be saved; the encrypted audio, its DRM keys, and the cover are copied unchanged. Edited files have been checked with ffprobe, ffmpeg, and ExifTool, not with Audible's own apps, which may check a digest the file stores (the purpose of the `68ec733412b9` key is unknown). Keep a copy of the original, or save to a new path. Audible `.aax` is MPEG-4 and opens as MP4/M4A, with its audiobook atoms (narrator, short and parent titles, product IDs, release date) as named properties. Decryption is out of scope.
- AVI (`.avi`, including OpenDML): RIFF INFO and `ID32` (ID3v2) tags, duration, video size, frame rate and FourCC, and the first audio stream. Tags are saved without changing the `movi` sample data; every `idx1` and OpenDML index stays valid. INFO text follows the RIFF `CSET` chunk (ISO 8859-1 when there is none): 65001, 1252, 0 and 28591 are decoded, and with no `CSET` valid UTF-8 (what ffmpeg and TagLib# write) is read as UTF-8 and other text as Windows-1252. On save, a value you did not change keeps its exact bytes and the file keeps its `CSET`; changed values are written in the file's code page when they fit it (with no `CSET`, ASCII only), otherwise the list becomes UTF-8 with a `CSET` of code page 65001 before it, which ffprobe, TagLib# and exiftool read (mediainfo ignores `CSET`). When the list becomes UTF-8, untouched text in a declared code page that is decoded exactly (1252, 28591, 0) is rewritten as the same text in UTF-8; the save is refused, with an error naming the field and the reason, when an untouched value's code page is only a guess (no `CSET`), is not decoded here (Shift-JIS, cp1251, ...), or the value holds a byte its declared code page leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D in 1252; 0x80-0x9F under code page 0). The new `CSET` keeps the old one's country, language and dialect codes. The five undefined 1252 code points are written as UTF-8, never as 1252 bytes. A save loads the whole file into memory (about one file's worth when nothing moves, two when the data has to move), so AVI files of 2 GiB or more cannot be saved yet; reading has no such limit.
+ - Still images: JPEG, PNG, GIF, BMP, PCX, Netpbm (`.pbm`, `.pgm`, `.ppm`, `.pnm`), TIFF, DNG, and SVG open through `MediaFile.Read` or `StillImageFile.ReadFromFile` with width and height. PNG text, the GIF comment, and the JPEG COM marker can be edited; a PNG edit also updates the XMP and Exif copies of the field. Other image metadata is not read or written yet.
## Format Support Matrix
diff --git a/docs/IMPLEMENTATION-GUIDE.md b/docs/IMPLEMENTATION-GUIDE.md
index a1b1b91d..f9e5148a 100644
--- a/docs/IMPLEMENTATION-GUIDE.md
+++ b/docs/IMPLEMENTATION-GUIDE.md
@@ -134,6 +134,16 @@ how it was broken before.
- **Fields the format requires** are kept: the Vorbis comment vendor string, which the header must
carry (Xiph Vorbis comment, "vendor_length / vendor_string"), and Matroska's mandatory `MuxingApp`
and `WritingApp` (RFC 9559).
+ - **Segments a decoder or colour management needs, or that carry the file's structure**, are kept: in
+ still images, JPEG APP0 JFIF/JFXX, APP2 ICC_PROFILE, APP2 MPF (the multi-picture index; its offsets and
+ sizes are rewritten, and Clear cleans every image it lists), APP2 ISO 21496-1 (gain map), APP14 Adobe
+ (colour transform), the gain-map XMP properties an HDR decoder needs (Ultra HDR `hdrgm` and the
+ `Container`/`Item` directory with only the item values the formats enumerate, Apple `apdi` and `HDRGainMap` version and headroom, motion-photo `Camera` flags, each with the value shape its format defines, written into a new packet; nothing of the original packet is copied.) and, for a version-65536 Apple gain map, a new Exif holding only Apple maker-note tags 33 and 48 (the headroom ImageIO and libultrahdr compute from them; decode parameters, no personal data; when an Exif repeats a pointer, a MakerNote or a tag, the values kept are the ones ImageIO applies (`AppleHeadroom.Keep`); nothing else of the Exif is kept, so it is a minimal carrier that omits Exif's mandatory format tags and `exiftool -validate` warns, while every tested reader reads it), and the APP11 JPEG
+ XT decoding boxes named in public sources (`ftyp`, `TONE`, `RTRF`, `LTRF`, `LCHK`, `SPEC`, `RESI`); PNG critical chunks and the decode/colour chunks (tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI,
+ sBIT, bKGD, hIST, pHYs, sPLT, the APNG chunks, oFFs, pCAL, sCAL, sTER); GIF graphic control and plain text
+ extensions, NETSCAPE2.0/ANIMEXTS1.0 looping and ICCRGBG1012. Everything else goes, including C2PA
+ manifests (PNG caBX, JPEG APP11 JUMBF), which any edit invalidates, every other APP11 box (`xml `,
+ `uuid`, `json`, `Exif` and unknown ones carry metadata), and unknown APPn, chunks and extensions.
- **Chapters** are file structure, not tag metadata. A tag `Clear()` keeps them in Matroska and in MP4
(checked on main: ffprobe lists the same chapters after a Clear and a save). Use the chapter API to
remove them.
@@ -240,6 +250,8 @@ A fix is new code, so steps (b) to (e) apply to it in full.
| `Bounds.AllocatedBytes (action)` | Bytes allocated on this thread while `action` runs. Synchronous code only. |
| `Bounds.AssertAllocatesAtMost (limit, action)` | Fails with the count when a parse allocates past a bound. |
| `Bounds.AssertLinearAllocation (build, run, n)` | Measures n, 2n and 4n, and fails when the second increment is more than 3× the first (linear work is 2×). This catches quadratic copies even behind a fixed cost. |
+| `Bounds.LeastAllocated (action)` | The least bytes `action` allocates after one warm-up, so a single noisy run does not set the bound. |
+| `Bytes.Count (data, needle)` | How many times a byte sequence occurs in `data`, including overlaps. |
| `CountingStream` | Counts bytes read, reads and seeks, to pin that a stream path reads only what it needs. |
| `Hostile.EveryTruncation (valid, read)` | Runs every prefix through `read`, then reports how many threw and the first lengths. |
| `Hostile.ByteFlips (valid, read)` | Changes each byte to 0x00 and 0xFF and XORs it with 0x01 and 0x80, reporting the offset and value of each throw. `values:` sets the replacement values. |
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 79b8da97..41e6e98d 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2,11 +2,11 @@
> Generated: January 2026
> Last Updated: November 2026
-> Status: Production ready - 18 formats read and write tags, polish phase
+> Status: Production ready - audio and video formats read and write tags; still images open with dimensions, polish phase
## Executive Summary
-TagLibSharp2 currently supports **18 formats** with read and write. The library has mature read/write capabilities for all major formats. Remaining gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). A path save copies the audio in 64 KB pieces instead of loading the file. `Render` and a save from a span still build one buffer.
+TagLibSharp2 reads and writes tags for the audio and video formats below. JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, and SVG open with width and height. PNG text keywords, the GIF comment, and the JPEG COM marker can be edited. A field edit also removes that field's Exif copies when the Exif structure is plain, and updates the matching XMP property; any other Exif structure is refused and nothing is written. Exif values are not read into the tag. IPTC is not read or written, and SVG metadata is not read or written yet. Remaining audio gaps are niche formats: Speex (obsolete), TrueAudio (niche), and tracker formats (demoscene). Matroska/WebM saves tag values, chapters, and picture attachments. A path save copies the audio in 64 KB pieces instead of loading the file. `Render` and a save from a span still build one buffer.
---
@@ -31,6 +31,7 @@ TagLibSharp2 currently supports **18 formats** with read and write. The library
| Matroska/WebM | P2 | ✅ | ✅ | ✅ | - | Tag values, chapters, picture attachments, and track enabled flags are saved. Other attachments are preserved, not rewritten |
| MPEG PS / video ES | P2 | ✅ | ✅ | ✅ | - | ID3v2 and ID3v1 around the stream; duration from PTS or GOP time codes |
| AVI (incl. OpenDML) | P2 | ✅ | ✅ | ✅ | - | RIFF INFO and ID32 tags; movi and every index kept valid. A path save copies movi in 64 KB pieces |
+| JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, SVG | P2 | ✅ | Dimensions | PNG text, GIF comment, JPEG COM, plain Exif removal, matching XMP | - | A path save copies pixels in 64 KB pieces. Render still copies every other byte. A field edit removes Exif copies only when the structure is plain, and refuses otherwise. IPTC is not read or written. SVG metadata is not read or written yet |
| Ogg FLAC | P1 | ✅ | ✅ | ✅ | - | Recently added |
| AAC (ADTS/ADIF) | P1 | ✅ | ✅ | ✅ | - | ID3v2, APEv2, ID3v1 tags |
| Speex | P1 | ❌ | ❌ | ❌ | LOW | Uses Vorbis Comment |
diff --git a/src/TagLibSharp2/Core/AtomicFileWriter.cs b/src/TagLibSharp2/Core/AtomicFileWriter.cs
index 1a0e733a..251061bc 100644
--- a/src/TagLibSharp2/Core/AtomicFileWriter.cs
+++ b/src/TagLibSharp2/Core/AtomicFileWriter.cs
@@ -186,6 +186,10 @@ internal static FileWriteResult WriteStream (string path, IFileSystem? fileSyste
destinationExisted = fileSystem.FileExists (path);
fileSystem.Move (tempPath, path);
return FileWriteResult.Success (ReportedBytes (bytesWritten));
+ } catch (OperationCanceledException) {
+ if (tempPath is not null)
+ CleanupTempFile (tempPath, fileSystem);
+ return FileWriteResult.Failure ("Operation was cancelled");
} catch (EndOfStreamException ex) {
return FailWrite (
tempPath,
diff --git a/src/TagLibSharp2/Core/BinaryData.cs b/src/TagLibSharp2/Core/BinaryData.cs
index 681c28cc..9ac2e037 100644
--- a/src/TagLibSharp2/Core/BinaryData.cs
+++ b/src/TagLibSharp2/Core/BinaryData.cs
@@ -979,11 +979,16 @@ static ushort[] BuildCrc16CcittTable ()
/// Computes CRC-32 using the standard polynomial (0xEDB88320).
/// This is compatible with zlib/PNG CRC.
///
- public uint ComputeCrc32 ()
+ public uint ComputeCrc32 () => ComputeCrc32 (Data);
+
+ ///
+ /// Computes CRC-32 over without copying it.
+ ///
+ internal static uint ComputeCrc32 (ReadOnlySpan data)
{
var crc = 0xFFFFFFFF;
- for (var i = 0; i < Data.Length; i++)
- crc = Crc32Table[(crc ^ Data[i]) & 0xFF] ^ (crc >> 8);
+ for (var i = 0; i < data.Length; i++)
+ crc = Crc32Table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
return ~crc;
}
diff --git a/src/TagLibSharp2/Core/MediaFile.cs b/src/TagLibSharp2/Core/MediaFile.cs
index 801afa0d..19288e6a 100644
--- a/src/TagLibSharp2/Core/MediaFile.cs
+++ b/src/TagLibSharp2/Core/MediaFile.cs
@@ -2,6 +2,7 @@
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System.Buffers.Binary;
+using System.Runtime.InteropServices;
using TagLibSharp2.Aac;
using TagLibSharp2.Aiff;
using TagLibSharp2.Ape;
@@ -9,6 +10,7 @@
using TagLibSharp2.Audible;
using TagLibSharp2.Dff;
using TagLibSharp2.Dsf;
+using TagLibSharp2.Image;
using TagLibSharp2.Matroska;
using TagLibSharp2.Mp4;
using TagLibSharp2.Mpeg;
@@ -416,6 +418,9 @@ static async Task ReadAsync (
MediaFormat.MpegPs => FromMpegPs (await MpegPsFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)),
MediaFormat.Audible => FromAudible (await AudibleFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)),
MediaFormat.Avi => FromAvi (await AviFile.ReadAsync (stream, sourcePath, fileSystem, cancellationToken).ConfigureAwait (false)),
+ MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif or MediaFormat.Bmp or MediaFormat.Pcx
+ or MediaFormat.Netpbm or MediaFormat.Tiff or MediaFormat.Dng or MediaFormat.Svg
+ => OpenImage (await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false), format),
_ => OpenDetected (format, stream, sourcePath, fileSystem, pathHint)
};
return RememberMatroskaSource (result, sourcePath, fileSystem);
@@ -445,11 +450,15 @@ static MediaFileResult OpenDetected (MediaFormat format, Stream stream, string?
_ => ReadFromData (StreamBytes.ReadToEnd (stream), pathHint)
};
- // ReadFromData's path is only an extension hint. A path read can save Matroska back to that file.
+ // ReadFromData's path is only an extension hint. A path read can save Matroska and still images back to that file.
static MediaFileResult RememberMatroskaSource (MediaFileResult result, string? sourcePath, IFileSystem? fileSystem)
{
- if (sourcePath is not null && result.IsSuccess && result.File is MatroskaFile matroska)
+ if (sourcePath is null || !result.IsSuccess)
+ return result;
+ if (result.File is MatroskaFile matroska)
matroska.SetSourcePath (sourcePath, fileSystem);
+ else if (result.File is StillImageFile image)
+ image.SetSource (sourcePath, fileSystem);
return result;
}
@@ -627,6 +636,8 @@ static MediaFileResult ReadCore (ReadOnlyMemory data, string? pathHint)
MediaFormat.Aac => FromAac (AacFile.Read (data)),
MediaFormat.Audible => FromAudible (AudibleFile.Read (data.Span)),
MediaFormat.Avi => FromAvi (AviFile.Read (data.Span)),
+ MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif or MediaFormat.Bmp or MediaFormat.Pcx
+ or MediaFormat.Netpbm or MediaFormat.Tiff or MediaFormat.Dng or MediaFormat.Svg => OpenImage (data, format),
_ => MediaFileResult.Failure ($"Unknown or unsupported file format{(pathHint is not null ? $": {pathHint}" : "")}")
};
@@ -751,6 +762,11 @@ static MediaFormat DetectFormat (ReadOnlySpan data, string? pathHint, Stre
if (MpegFrame.IsStartOfAudio (data))
return MediaFormat.Mp3;
+ // After the audio signatures. A markup check that decoded every unknown buffer
+ // would copy an MP3, an ID3 tag, or an ASF header on the way to "not an image".
+ if (data.Length >= 4 && ImageHeader.TryDetect (data, out var image))
+ return image == MediaFormat.Tiff && StillImageFile.HasDngName (pathHint) ? MediaFormat.Dng : image;
+
// Fall back to extension
if (!string.IsNullOrEmpty (pathHint)) {
var ext = Path.GetExtension (pathHint).ToUpperInvariant ();
@@ -774,6 +790,15 @@ static MediaFormat DetectFormat (ReadOnlySpan data, string? pathHint, Stre
".MPG" or ".MPEG" or ".MPE" or ".VOB" or ".MPV" or ".M1V" or ".M2V" => MediaFormat.MpegPs,
".AAC" => MediaFormat.Aac,
".AVI" => MediaFormat.Avi,
+ ".JPG" or ".JPEG" or ".JPE" => MediaFormat.Jpeg,
+ ".PNG" => MediaFormat.Png,
+ ".GIF" => MediaFormat.Gif,
+ ".BMP" or ".DIB" => MediaFormat.Bmp,
+ ".PCX" => MediaFormat.Pcx,
+ ".PBM" or ".PGM" or ".PPM" or ".PNM" => MediaFormat.Netpbm,
+ ".TIF" or ".TIFF" => MediaFormat.Tiff,
+ ".DNG" => MediaFormat.Dng,
+ ".SVG" => MediaFormat.Svg,
_ => MediaFormat.Unknown
};
}
@@ -950,6 +975,28 @@ static MediaFileResult OpenMonkeysAudio (ReadOnlyMemory data)
return MediaFileResult.Success (result.File!, result.File!.ApeTag, MediaFormat.MonkeysAudio);
}
+ static MediaFileResult OpenImage (ReadOnlyMemory data, MediaFormat format)
+ {
+ var opened = StillImageFile.Open (OwnedBytes (data), format);
+ return opened.IsSuccess
+ ? MediaFileResult.Success (opened.File!, opened.File!.Tag, format)
+ : MediaFileResult.Failure (opened.Error!);
+ }
+
+ // Reuse the array behind a memory that already owns the whole buffer. A slice is copied.
+ static byte[] OwnedBytes (ReadOnlyMemory data)
+ {
+ if (MemoryMarshal.TryGetArray (data, out ArraySegment segment)
+ && segment.Array is byte[] array
+ && segment.Offset == 0
+ && segment.Count == array.Length
+ && data.Length == array.Length)
+ return array;
+
+ return data.ToArray ();
+ }
+
+
static MediaFileResult OpenAsf (ReadOnlyMemory data)
{
var result = AsfFile.Read (data.Span);
@@ -1141,5 +1188,32 @@ public enum MediaFormat
///
/// AVI (RIFF AVI form, including OpenDML).
///
- Avi
+ Avi,
+
+ /// JPEG still image.
+ Jpeg,
+
+ /// PNG still image.
+ Png,
+
+ /// GIF still image.
+ Gif,
+
+ /// BMP still image.
+ Bmp,
+
+ /// PCX still image.
+ Pcx,
+
+ /// Netpbm raster (PBM, PGM, PPM, or PNM).
+ Netpbm,
+
+ /// TIFF still image.
+ Tiff,
+
+ /// DNG, a TIFF file with the DNG version tag or a .dng name.
+ Dng,
+
+ /// SVG image.
+ Svg
}
diff --git a/src/TagLibSharp2/Core/Tag.cs b/src/TagLibSharp2/Core/Tag.cs
index d168fdb0..202aae56 100644
--- a/src/TagLibSharp2/Core/Tag.cs
+++ b/src/TagLibSharp2/Core/Tag.cs
@@ -72,6 +72,11 @@ public enum TagTypes
///
Audible = 1 << 10,
+ ///
+ /// Text stored in a still image: PNG keywords, a GIF comment, or a JPEG COM marker.
+ ///
+ Image = 1 << 11,
+
///
/// All tag types.
///
diff --git a/src/TagLibSharp2/Image/Endian.cs b/src/TagLibSharp2/Image/Endian.cs
new file mode 100644
index 00000000..a64ecbad
--- /dev/null
+++ b/src/TagLibSharp2/Image/Endian.cs
@@ -0,0 +1,51 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Buffers.Binary;
+
+namespace TagLibSharp2.Image;
+
+///
+/// Reads and writes unsigned integers in either byte order over spans: the one byte-order helper of the image
+/// code (TIFF and Exif "II"/"MM", the MPF index, PNG chunk fields, BMP headers).
+///
+static class Endian
+{
+ public static int U16 (ReadOnlySpan data, int at, bool le) =>
+ le ? BinaryPrimitives.ReadUInt16LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt16BigEndian (data.Slice (at));
+
+ public static long U32 (ReadOnlySpan data, int at, bool le) =>
+ le ? BinaryPrimitives.ReadUInt32LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt32BigEndian (data.Slice (at));
+
+ public static int I32 (ReadOnlySpan data, int at, bool le) =>
+ le ? BinaryPrimitives.ReadInt32LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadInt32BigEndian (data.Slice (at));
+
+ /// False outside the data, or for a value above .
+ public static bool TryU64 (ReadOnlySpan data, int at, bool le, out long value)
+ {
+ value = 0;
+ if (at < 0 || at > data.Length - 8)
+ return false;
+ var raw = le ? BinaryPrimitives.ReadUInt64LittleEndian (data.Slice (at)) : BinaryPrimitives.ReadUInt64BigEndian (data.Slice (at));
+ if (raw > long.MaxValue)
+ return false;
+ value = (long)raw;
+ return true;
+ }
+
+ public static void WriteU16 (Span data, int at, int value, bool le)
+ {
+ if (le)
+ BinaryPrimitives.WriteUInt16LittleEndian (data.Slice (at), (ushort)value);
+ else
+ BinaryPrimitives.WriteUInt16BigEndian (data.Slice (at), (ushort)value);
+ }
+
+ public static void WriteU32 (Span data, int at, long value, bool le)
+ {
+ if (le)
+ BinaryPrimitives.WriteUInt32LittleEndian (data.Slice (at), (uint)value);
+ else
+ BinaryPrimitives.WriteUInt32BigEndian (data.Slice (at), (uint)value);
+ }
+}
diff --git a/src/TagLibSharp2/Image/Exif/AppleHeadroom.cs b/src/TagLibSharp2/Image/Exif/AppleHeadroom.cs
new file mode 100644
index 00000000..719462d0
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/AppleHeadroom.cs
@@ -0,0 +1,231 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image.Exif;
+
+///
+/// The HDR headroom a version-65536 Apple gain map takes from the primary image's Apple maker note, and the minimal
+/// Exif that keeps it after Clear.
+///
+static class AppleHeadroom
+{
+ const int MakerNoteTag = 0x927C;
+ const int HeadroomTag = 0x0021;
+ const int GainTag = 0x0030;
+ const int SRationalType = 10;
+
+ static ReadOnlySpan MakerNoteHeader => "Apple iOS\0\0\u0001MM"u8;
+
+ ///
+ /// The Exif a version-65536 Apple gain map needs after Clear: a big-endian TIFF with IFD0 -> Exif IFD ->
+ /// MakerNote, and in the Apple maker note only tags 0x0021 and 0x0030, copied as stored. Null when the
+ /// values ImageIO would apply are not both there as one SRATIONAL each.
+ ///
+ ///
+ /// Apple, "Applying Apple HDR effect to your photos"
+ /// (https://developer.apple.com/documentation/appkit/applying-apple-hdr-effect-to-your-photos): a gain map
+ /// whose metadata has HDRGainMapVersion takes its headroom from the MakerNote keys 33 and 48.
+ /// They are decode parameters, not personal data. The maker note (Exif 2.32 §4.6.5, tag 0x927C, UNDEFINED)
+ /// starts "Apple iOS", NUL, version 1, "MM", then a big-endian IFD whose value offsets count from the start of
+ /// the maker note.
+ /// TIFF 6.0 does not say which of two entries with one tag wins, or what a reader does with one it cannot
+ /// use, so the values kept are the ones ImageIO applies, measured on ImageIO-written files with every level
+ /// duplicated and broken. Where libultrahdr differs, this follows ImageIO, Apple's decoder for Apple's format.
+ /// At every level an occurrence that cannot be used is skipped and a later usable one overrides an earlier one:
+ ///
+ /// - IFD0 0x8769 (Exif IFD pointer): usable when LONG or IFD, count 1, and its table lies inside the data.
+ /// Two Exif IFDs merge tag by tag: a later one's maker-note value replaces an earlier one's, and a later Exif
+ /// IFD without one leaves the earlier one's (libultrahdr reads only the first pointer and refuses the file
+ /// when that one is out of range);
+ /// - Exif IFD 0x927C (MakerNote): usable when UNDEFINED, more than 4 bytes, inside the data, and either not
+ /// an Apple maker note (it then wins with no values, so nothing is kept) or one whose header is exactly as above
+ /// and whose entry table fits; an Apple maker note with another header or a table that does not fit is skipped.
+ /// The last usable one of an Exif IFD is that IFD's maker note, whole (libultrahdr reads the first);
+ /// - maker-note 0x0021 and 0x0030: usable when SRATIONAL, count at least 1 and the 8 bytes of each value
+ /// inside the maker note, at any offset (its header and entry table included). The last usable one of each tag
+ /// wins. When a winner's count is not 1 ImageIO renders no HDR image at all, so nothing is kept (libultrahdr
+ /// reads the first value regardless of the count, and refuses a value outside the maker note).
+ ///
+ /// The Exif segment is the first one (both decoders use the first), and its TIFF header must carry the magic 42
+ /// (ImageIO ignores an Exif without it).
+ /// The result is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately
+ /// omits the tags Exif marks mandatory (ExifVersion, ComponentsConfiguration, ColorSpace, the pixel dimensions,
+ /// YCbCrPositioning and the resolution tags, CIPA DC-008 §4.6.8), consistent with Clear removing all other
+ /// Exif, so exiftool -validate warns about them. ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# read
+ /// it.
+ /// Each distinct Exif IFD and maker note is walked once, from the last, and every entry visit is counted
+ /// in ; the entries walked are bounded by the data (tables that overlap past it keep
+ /// nothing); nothing recurses and nothing throws.
+ ///
+ internal static byte[]? Keep (ReadOnlySpan data)
+ {
+ // A header that is not classic TIFF (byte order and magic 42) keeps nothing: ImageIO ignores that Exif.
+ if (!TiffReader.TryClassic (data, out var tiff, out var ifd0) || !tiff.TryTable (ifd0, out var ifd0Count))
+ return null;
+ var pointers = ExifIfdPointers (tiff, ifd0, ifd0Count);
+ var (headroom, gain) = FindWinners (tiff, pointers);
+ if (headroom.Count != 1 || gain.Count != 1)
+ return null;
+ return HeadroomTiff (data.Slice ((int)headroom.At, 8), data.Slice ((int)gain.At, 8));
+ }
+
+ // The last usable entry of a tag: its value's offset in the TIFF and its count (0 when there is none).
+ readonly record struct Winner (long At, long Count)
+ {
+ public bool Found => Count > 0;
+ }
+
+ // Later Exif IFDs override earlier ones tag by tag: walking from the last, the first value found for a tag is
+ // the one that wins, and an Exif IFD seen again adds nothing. The walk stops when both are found, or when the
+ // entries walked pass the bound of one per 12 bytes (tables that overlap past it keep nothing: every value needs a
+ // maker note entry, so none can be found past the bound).
+ static (Winner Headroom, Winner Gain) FindWinners (TiffReader tiff, CountedList pointers)
+ {
+ var (headroom, gain) = (default (Winner), default (Winner));
+ var budget = tiff.EntryBound;
+ var seen = new HashSet ();
+ for (var p = pointers.Count - 1; p >= 0 && (!headroom.Found || !gain.Found); p--) {
+ var ifd = pointers[p];
+ if (!seen.Add (ifd))
+ continue;
+ _ = tiff.TryTable (ifd, out var count);
+ budget -= count;
+ var found = ReadMakerNote (tiff, ifd, count, ref budget);
+ if (budget < 0)
+ return (default (Winner), default (Winner));
+ if (!headroom.Found)
+ headroom = found.Headroom;
+ if (!gain.Found)
+ gain = found.Gain;
+ }
+
+ return (headroom, gain);
+ }
+
+ // The headroom entries of an Exif IFD's Apple maker note, with offsets in the TIFF (none when its maker note is
+ // not Apple's); its entries are taken from the budget.
+ static (Winner Headroom, Winner Gain) ReadMakerNote (TiffReader tiff, long ifd, int count, ref long budget)
+ {
+ // A usable maker note that starts with Apple's header has an entry table that fits (IsUsable).
+ if (LastMakerNote (tiff, ifd, count) is not var (noteAt, noteSize))
+ return default;
+ var note = tiff.Data.Slice ((int)noteAt, (int)noteSize);
+ if (!note.StartsWith (MakerNoteHeader))
+ return default;
+ // The entry count IsUsable already required to fit. It is the same count the maker-note walk reads.
+ var noteReader = new TiffReader (note, littleEndian: false);
+ if (!noteReader.TryTable (MakerNoteHeader.Length, out var entries))
+ return default;
+ budget -= entries;
+ var (headroom, gain) = HeadroomEntries (noteReader);
+ return (headroom with { At = noteAt + headroom.At }, gain with { At = noteAt + gain.At });
+ }
+
+ // The Exif IFD pointers ImageIO follows: LONG or IFD, count 1, a table inside the data; in IFD0 order.
+ static CountedList ExifIfdPointers (TiffReader tiff, long ifd0, int ifd0Count)
+ {
+ var pointers = new CountedList ();
+ for (var n = 0; n < ifd0Count; n++) {
+ IfdSteps.Count++;
+ var entry = tiff.Entry (ifd0, n);
+ if (tiff.Tag (entry) != TiffReader.ExifIfdPointer || tiff.Type (entry) is not (4 or 13) || tiff.Count (entry) != 1)
+ continue;
+ var at = tiff.Value (entry);
+ if (tiff.TryTable (at, out _))
+ pointers.Add (at);
+ }
+
+ return pointers;
+ }
+
+ // The maker note of an Exif IFD as ImageIO takes it: the last usable 0x927C entry (UNDEFINED, more than 4
+ // bytes, inside the data; an Apple maker note only with its exact header and a table that fits), or null.
+ static (long At, long Size)? LastMakerNote (TiffReader tiff, long ifd, int count)
+ {
+ (long At, long Size)? note = null;
+ for (var n = 0; n < count; n++) {
+ IfdSteps.Count++;
+ var entry = tiff.Entry (ifd, n);
+ if (tiff.Tag (entry) != MakerNoteTag || tiff.Type (entry) != 7)
+ continue;
+ var size = tiff.Count (entry);
+ var at = tiff.Value (entry);
+ if (size <= 4 || size > tiff.Length - at)
+ continue;
+ if (IsUsable (tiff.Data.Slice ((int)at, (int)size)))
+ note = (at, size);
+ }
+
+ return note;
+ }
+
+ // Another maker note is usable as it is; an Apple one only with its exact header and an entry table that fits.
+ // The maker note is a big-endian IFD at offset 14 of its own bytes (14 is past the classic header).
+ static bool IsUsable (ReadOnlySpan bytes)
+ {
+ if (!bytes.StartsWith (MakerNoteHeader.Slice (0, 10)))
+ return true;
+ if (!bytes.StartsWith (MakerNoteHeader))
+ return false;
+ return new TiffReader (bytes, littleEndian: false).TryTable (MakerNoteHeader.Length, out _);
+ }
+
+ // The last usable 0x0021 and 0x0030 entries of an Apple maker note: SRATIONAL, count at least 1, every value
+ // inside the maker note (any offset). Offsets count from the maker note. The IFD is the one TiffReader reads.
+ static (Winner Headroom, Winner Gain) HeadroomEntries (TiffReader tiff)
+ {
+ if (!tiff.TryTable (MakerNoteHeader.Length, out var count))
+ return default;
+ var (headroom, gain) = (default (Winner), default (Winner));
+ for (var n = 0; n < count; n++) {
+ IfdSteps.Count++;
+ var entry = tiff.Entry (MakerNoteHeader.Length, n);
+ var tag = tiff.Tag (entry);
+ if ((tag != HeadroomTag && tag != GainTag) || tiff.Type (entry) != SRationalType)
+ continue;
+ var values = tiff.Count (entry);
+ var offset = tiff.Value (entry);
+ if (values == 0 || values > (tiff.Length - offset) / 8)
+ continue;
+ if (tag == HeadroomTag)
+ headroom = new Winner (offset, values);
+ else
+ gain = new Winner (offset, values);
+ }
+
+ return (headroom, gain);
+ }
+
+ // TIFF header, IFD0 at 8 (the Exif IFD pointer), the Exif IFD at 26 (the maker note), the maker note at 44:
+ // its header, two entries, a zero next-IFD offset, and the two values at 44 and 52 of the maker note.
+ static byte[] HeadroomTiff (ReadOnlySpan headroom, ReadOnlySpan gain)
+ {
+ const int ExifAt = 26;
+ const int NoteAt = 44;
+ const int NoteLength = 14 + 2 + 24 + 4 + 16;
+ var output = new byte[NoteAt + NoteLength];
+ "MM\0*"u8.CopyTo (output);
+ Endian.WriteU32 (output, 4, 8, le: false);
+ Endian.WriteU16 (output, 8, 1, le: false);
+ WriteEntry (output, 10, TiffReader.ExifIfdPointer, 4, 1, ExifAt);
+ Endian.WriteU16 (output, ExifAt, 1, le: false);
+ WriteEntry (output, ExifAt + 2, MakerNoteTag, 7, NoteLength, NoteAt);
+ MakerNoteHeader.CopyTo (output.AsSpan (NoteAt));
+ Endian.WriteU16 (output, NoteAt + 14, 2, le: false);
+ WriteEntry (output, NoteAt + 16, HeadroomTag, SRationalType, 1, 44);
+ WriteEntry (output, NoteAt + 28, GainTag, SRationalType, 1, 52);
+ headroom.CopyTo (output.AsSpan (NoteAt + 44));
+ gain.CopyTo (output.AsSpan (NoteAt + 52));
+ return output;
+
+ static void WriteEntry (byte[] data, int at, int tag, int type, int count, int value)
+ {
+ Endian.WriteU16 (data, at, tag, le: false);
+ Endian.WriteU16 (data, at + 2, type, le: false);
+ Endian.WriteU32 (data, at + 4, count, le: false);
+ Endian.WriteU32 (data, at + 8, value, le: false);
+ }
+ }
+}
diff --git a/src/TagLibSharp2/Image/Exif/ByteRanges.cs b/src/TagLibSharp2/Image/Exif/ByteRanges.cs
new file mode 100644
index 00000000..4b07ba6d
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/ByteRanges.cs
@@ -0,0 +1,50 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image.Exif;
+
+/// Sorted, merged byte ranges and the overlap test the Exif removal uses on them.
+static class ByteRanges
+{
+ public static CountedList<(long Start, long End)> Merge (CountedList<(long Start, long End)> ranges)
+ {
+ ranges.Sort ((a, b) => a.Start.CompareTo (b.Start));
+ var merged = new CountedList<(long Start, long End)> ();
+ for (var n = 0; n < ranges.Count; n++) {
+ var range = ranges[n];
+ if (range.End <= range.Start)
+ continue;
+ if (merged.Count > 0 && range.Start <= merged[merged.Count - 1].End)
+ merged[merged.Count - 1] = (merged[merged.Count - 1].Start, Math.Max (merged[merged.Count - 1].End, range.End));
+ else
+ merged.Add (range);
+ }
+
+ return merged;
+ }
+
+ /// The first range whose end is past , or sorted.Count when none is.
+ public static int FirstEndingAfter (CountedList<(long Start, long End)> sorted, long start)
+ {
+ int low = 0, high = sorted.Count;
+ while (low < high) {
+ IfdSteps.Count++;
+ var mid = low + ((high - low) / 2);
+ if (sorted[mid].End <= start)
+ low = mid + 1;
+ else
+ high = mid;
+ }
+
+ return low;
+ }
+
+ // The merged ranges are disjoint and sorted, so their ends are sorted too.
+ public static bool Overlaps (CountedList<(long Start, long End)> merged, (long Start, long End) range)
+ {
+ var low = FirstEndingAfter (merged, range.Start);
+ return low < merged.Count && merged[low].Start < range.End;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Exif/ExifCarrier.cs b/src/TagLibSharp2/Image/Exif/ExifCarrier.cs
new file mode 100644
index 00000000..32dab3d6
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/ExifCarrier.cs
@@ -0,0 +1,33 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+namespace TagLibSharp2.Image.Exif;
+
+///
+/// A block that holds an Exif TIFF: a JPEG APP1 segment, a PNG eXIf chunk, or an ImageMagick raw EXIF profile.
+/// Each may start with the "Exif\0\0" signature (CIPA DC-008 §4.7.2); the edited TIFF is wrapped back the way the
+/// block stores it, so never depends on the format.
+///
+/// Names the block in a refusal, such as "eXIf".
+/// Builds the block's new bytes around the edited TIFF (with its signature, when it had one).
+sealed class ExifCarrier (string name, Func wrap)
+{
+ public string Name { get; } = name;
+
+ /// Removes the changed fields' copies from the TIFF in .
+ /// The Exif bytes, with or without the signature.
+ /// The tag whose changed fields are removed.
+ /// The block's new bytes, or null when nothing changed.
+ /// Why the copy cannot be updated.
+ public bool TryEdit (ReadOnlySpan block, ImageTag tag, out byte[]? rewritten, out string? error)
+ {
+ rewritten = null;
+ var exif = block.ToArray ();
+ var start = block.StartsWith ("Exif\0\0"u8) ? 6 : 0;
+ if (!ExifEditor.TryRemove (exif, start, tag, Name, out var changed, out error))
+ return false;
+ if (changed)
+ rewritten = wrap (exif);
+ return true;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Exif/ExifEditor.cs b/src/TagLibSharp2/Image/Exif/ExifEditor.cs
new file mode 100644
index 00000000..67a6b1a6
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/ExifEditor.cs
@@ -0,0 +1,216 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image.Exif;
+
+///
+/// Removes each changed field's Exif entries (all its tags) from every table exiftool reads with its Exif tags:
+/// IFD0 and the chain of IFDs after it, and every Exif IFD (0x8769), SubIFD (0x014A) and interoperability IFD
+/// (0xA005) any of those points at, however deep, each pointer decoded as exiftool decodes it
+/// (, ; ImageIO reads a subset), and the Exif IFD that
+/// IFD0's 0x8769 field names read as a LONG whatever its type and count, as TagLib# reads it. GPS tables are
+/// read with GPS tags and left as they are. Each table is walked once. The entry table shrinks in place, so no offset
+/// moves. A field edit runs only when calls the structure plain and
+/// agrees. Anything else is refused and nothing is written.
+///
+///
+/// A field edit is refused when a removed value shares a protected byte, or when compacting a table would rewrite
+/// any protected range other than that table. Two protected ranges may share a byte; zeroing does not touch them.
+/// A pair given twice is not plain, and only the plainness check decides that. Skipping that check still applies
+/// the edit from the first of each pair. The plan's value-budget stop stays, so a skipped check cannot read every
+/// offset past half the bytes.
+///
+static class ExifEditor
+{
+ /// Compacting the edited tables would rewrite a protected range.
+ internal const string StructureWouldChange = "has IFD structure that removing the copy would change";
+
+ /// Two IFD tables share a byte, so neither can be compacted.
+ internal const string TablesOverlap = "has IFD tables that overlap each other";
+
+ /// A SubIFD offset array lies in a table the edit rewrites.
+ internal const string SubIfdInsideTable = "has SubIFD offsets inside an IFD table";
+
+ /// A kept value lies in a table the edit rewrites.
+ internal const string ValueInsideTable = "has a value inside an IFD table that the edit rewrites";
+
+ /// An IFD pointer names the middle of another table.
+ internal const string PointerIntoTable = "has an IFD pointer into the middle of another IFD table";
+
+ /// Set by tests to see the edit an unchecked removal would make (the matrix judges refusals by it).
+ [ThreadStatic]
+ internal static bool SkipCheck;
+
+ /// Removes the changed fields' entries from the TIFF at , in place.
+ ///
+ /// False, with an error and nothing written, when the block is not classic TIFF or its tables overlap past the
+ /// bound that keeps the walk linear, and its bytes could hold an entry with one of the fields' tags; and when
+ /// something is to be removed from structure that is not plain or not clean.
+ ///
+ internal static bool TryRemove (byte[] block, int start, ImageTag tag, string carrier, out bool changed, out string? error)
+ {
+ changed = false;
+ error = null;
+ if (!TryRequest (tag, out var tags, out var what))
+ return true;
+ var data = block.AsSpan (start);
+
+ // Refused, not skipped: a block that is not classic TIFF (another byte order mark, or the magic 43 of
+ // BigTIFF) may still be read by a reader that knows that form, so a copy in it cannot be known to be gone,
+ // unless none of the field's tags is in its bytes in either byte order: then no form can hold one.
+ if (!TiffReader.TryClassic (data, out var tiff, out var ifd0))
+ return (!HoldsAnyTag (data, tags, littleEndian: true, anyType: false) && !HoldsAnyTag (data, tags, littleEndian: false, anyType: false))
+ || Refuse ($"The {carrier} block is not a TIFF structure, so its copy of {what} cannot be updated.", out error);
+
+ // An IFD0 whose entries do not fit is read by no one (exiftool reports a bad IFD0 directory), and every other
+ // IFD is reached through it: there is no copy to update.
+ if (!tiff.TryTable (ifd0, out _))
+ return true;
+ var graph = IfdGraph.Walk (tiff, ifd0);
+
+ // Past the bound the walk stops, so a copy beyond it cannot be ruled out, unless none of the field's tags is
+ // in the block's bytes at all: then no table can hold one, and there is nothing to remove.
+ if (graph.OverBudget)
+ return !HoldsAnyTag (data, tags, tiff.LittleEndian, anyType: true)
+ || Refuse ($"The {carrier} block has IFD tables that overlap each other beyond what its data holds, so its copy of {what} cannot be updated.", out error);
+
+ // Plain structure is decided before any range is recorded or any value array is read. Nothing to remove
+ // leaves the block as it is, including when the structure is not plain.
+ var verdict = PlainExif.Judge (tiff, graph, tags);
+ if (!verdict.Removes)
+ return true;
+ if (!verdict.Plain && !SkipCheck)
+ return Refuse ($"The {carrier} block {verdict.Why}, so its copy of {what} cannot be updated.", out error);
+
+ var plan = RemovalPlan.Mark (tiff, graph, tags);
+ if (plan.Removing.Count == 0)
+ return true;
+ // The plan stopped before it had read every offset and length, so applying it could zero a strip, tile or
+ // thumbnail it never recorded. Nothing to remove never reaches here.
+ if (plan.ValueBudgetExceeded)
+ return Refuse ($"The {carrier} block {PlainExif.OverBudget}, so its copy of {what} cannot be updated.", out error);
+ // A removed value that shares a byte, or a table whose compaction would rewrite something a reader sees.
+ // Nothing is written. Two protected ranges may share a byte; zeroing does not touch them.
+ if (!SkipCheck && (!plan.IsClean () || CompactionConflict (graph, plan, carrier, what) is not null))
+ return Refuse (Reason (graph, plan, carrier, what), out error);
+ plan.Apply (block.AsSpan (start), tiff, graph);
+ changed = true;
+ return true;
+ }
+
+ static bool Refuse (string reason, out string? error)
+ {
+ error = reason;
+ return false;
+ }
+
+ // The tags of every changed field, and their names for a refusal; false when no changed field has Exif tags.
+ static bool TryRequest (ImageTag tag, out HashSet tags, out string what)
+ {
+ tags = [];
+ var names = new List ();
+ foreach (var field in MirrorFields.All) {
+ if (!tag.Changed (field.Store))
+ continue;
+ tags.UnionWith (field.Ifd0);
+ tags.UnionWith (field.ExifIfd);
+ names.Add (field.Name);
+ }
+
+ what = string.Join (", ", names);
+ return tags.Count > 0;
+ }
+
+ // Whether the bytes, at any offset, in the given byte order, could be an entry with one of the tags: the tag
+ // followed by any type (TagLib# reads a UserComment of any type) or, for a block that is not classic TIFF, by a
+ // field type a TIFF or BigTIFF reader knows (1-18). One pass.
+ static bool HoldsAnyTag (ReadOnlySpan data, HashSet tags, bool littleEndian, bool anyType)
+ {
+ for (var at = 0; at + 4 <= data.Length; at++) {
+ IfdSteps.Count++;
+ if (tags.Contains (Endian.U16 (data, at, littleEndian)) && (anyType || Endian.U16 (data, at + 2, littleEndian) is >= 1 and <= 18))
+ return true;
+ }
+
+ return false;
+ }
+
+ // Why a checked edit was refused: the structure the edit would rewrite, named from its shape.
+ static string Reason (IfdGraph graph, RemovalPlan plan, string carrier, string what) =>
+ CompactionConflict (graph, plan, carrier, what)
+ ?? StructureChange (carrier, what);
+
+ // The shape that explains a refusal, or null: a table being compacted shares a byte with another table, or an
+ // unread table's count, a pointer array or another kept value or data range lies in a table being compacted.
+ static string? CompactionConflict (IfdGraph graph, RemovalPlan plan, string carrier, string what)
+ {
+ if (CompactedRanges (graph, plan.Removing) is not CountedList<(long Start, long End)> compacted)
+ return Refusal (carrier, what, TablesOverlap);
+ for (var n = 0; n < graph.Unread.Count; n++) {
+ var at = graph.Unread[n];
+ if (ByteRanges.Overlaps (compacted, (at, at + 2)))
+ return Refusal (carrier, what, PointerIntoTable);
+ }
+
+ // A kept value inside a table being compacted would be rewritten: a SubIFD offset array (readers would follow it
+ // elsewhere), another entry's value, or the data an offset/length pair names.
+ for (var n = 0; n < plan.Kept.Count; n++) {
+ var (start, end, kind) = plan.Kept[n];
+ if (ByteRanges.Overlaps (compacted, (start, end)))
+ return Refusal (carrier, what, kind == TiffReader.SubIfdsPointer ? SubIfdInsideTable : ValueInsideTable);
+ }
+
+ // A protected range inside a table being compacted (a pointer's value, another table's bytes) would be
+ // rewritten. The table's own range is one of those protected ranges and is the edit, so it does not count.
+ for (var n = 0; n < plan.Protected.Count; n++) {
+ var range = plan.Protected[n];
+ if (!ByteRanges.Overlaps (compacted, range) || IsCompactedTable (compacted, range))
+ continue;
+ return StructureChange (carrier, what);
+ }
+
+ return null;
+ }
+
+ static string StructureChange (string carrier, string what) =>
+ Refusal (carrier, what, StructureWouldChange);
+
+ static string Refusal (string carrier, string what, string reason) =>
+ $"The {carrier} block {reason}, so its copy of {what} cannot be updated.";
+
+ // Compacted tables are sorted and disjoint, so the table a protected range names is one binary search.
+ static bool IsCompactedTable (CountedList<(long Start, long End)> compacted, (long Start, long End) range)
+ {
+ var low = ByteRanges.FirstEndingAfter (compacted, range.Start);
+ return low < compacted.Count && compacted[low].Start == range.Start && compacted[low].End == range.End;
+ }
+
+ // The sorted ranges of the tables being compacted, or null when one of them shares a byte with another table.
+ static CountedList<(long Start, long End)>? CompactedRanges (IfdGraph graph, Dictionary> removing)
+ {
+ var ranges = new CountedList<(long Start, long End, bool Compacted)> ();
+ for (var t = 0; t < graph.Tables.Count; t++) {
+ var (at, count, _) = graph.Tables[t];
+ var (rangeStart, rangeEnd) = TiffReader.TableRange (at, count);
+ ranges.Add ((rangeStart, rangeEnd, removing.ContainsKey (at)));
+ }
+
+ ranges.Sort ((a, b) => a.Start.CompareTo (b.Start));
+ var compacted = new CountedList<(long Start, long End)> ();
+ long furthest = long.MinValue, furthestCompacted = long.MinValue;
+ for (var n = 0; n < ranges.Count; n++) {
+ var range = ranges[n];
+ if (range.Start < furthestCompacted || (range.Compacted && range.Start < furthest))
+ return null;
+ furthest = Math.Max (furthest, range.End);
+ if (range.Compacted) {
+ furthestCompacted = Math.Max (furthestCompacted, range.End);
+ compacted.Add ((range.Start, range.End));
+ }
+ }
+
+ return compacted;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Exif/OffsetLengthPairs.cs b/src/TagLibSharp2/Image/Exif/OffsetLengthPairs.cs
new file mode 100644
index 00000000..5a3bc24a
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/OffsetLengthPairs.cs
@@ -0,0 +1,24 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+namespace TagLibSharp2.Image.Exif;
+
+///
+/// The offset/length pairs a plain edit may read: StripOffsets/StripByteCounts (0x0111/0x0117),
+/// TileOffsets/TileByteCounts (0x0144/0x0145) and JPEGInterchangeFormat/JPEGInterchangeFormatLength (0x0201/0x0202,
+/// TIFF 6.0 §3 and Exif 2.32 §4.6.5). Slot order is strip, tile, then thumbnail, the offset side then the length side.
+///
+static class OffsetLengthPairs
+{
+ public static readonly (int Offsets, int Lengths)[] All = [(0x0111, 0x0117), (0x0144, 0x0145), (0x0201, 0x0202)];
+
+ public static int Slot (int tag) => tag switch {
+ 0x0111 => 0,
+ 0x0117 => 1,
+ 0x0144 => 2,
+ 0x0145 => 3,
+ 0x0201 => 4,
+ 0x0202 => 5,
+ _ => -1
+ };
+}
diff --git a/src/TagLibSharp2/Image/Exif/PlainExif.cs b/src/TagLibSharp2/Image/Exif/PlainExif.cs
new file mode 100644
index 00000000..98279df5
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/PlainExif.cs
@@ -0,0 +1,187 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image.Exif;
+
+///
+/// Whether a field edit may run. One pass over the tables already walked, before a records
+/// a range or reads a value array. The structure is not plain when a classic next-IFD field has only one, two or
+/// three of its four bytes (TIFF 6.0 §2), when one table names the same strip, tile or thumbnail offset or length
+/// twice, when one of those is not SHORT or LONG, when one of those arrays does not lie wholly in the data, when
+/// one array is named twice, when removing an entry would change whether exiftool reads that table's first entry,
+/// or when a complete pair names more values than half the bytes. The first of these reasons stands; a later check
+/// does not replace it. An absent next field is plain. An empty table is read. A first-entry change that shows
+/// nothing new is still refused.
+///
+static class PlainExif
+{
+ /// A plain block, whether the edit removes an entry, and why it is not plain.
+ public readonly record struct Verdict (bool Plain, bool Removes, string? Why);
+
+ /// A classic next-IFD field has some, but not all, of its four bytes.
+ internal const string NextCutShort = "has an IFD whose next offset is cut short";
+
+ /// One table names the same strip, tile or thumbnail offset or length tag twice.
+ internal const string PairTagRepeated = "names a strip, tile or thumbnail offset or length more than once";
+
+ /// A strip, tile or thumbnail offset or length is not SHORT or LONG.
+ internal const string PairTypeWrong = "has a strip, tile or thumbnail offset or length that is not SHORT or LONG";
+
+ /// Two entries name one strip, tile or thumbnail array.
+ internal const string PairArrayRepeated = "names one strip, tile or thumbnail array more than once";
+
+ /// A strip, tile or thumbnail array does not lie wholly in the data.
+ internal const string PairDoesNotFit = "has a strip, tile or thumbnail array that does not fit in its data";
+
+ /// Removing an entry would change whether exiftool reads the table's first entry.
+ internal const string FirstEntryChanges = "would change whether exiftool reads a table's first entry";
+
+ /// Complete offset/length pairs name more values than half the bytes.
+ internal const string OverBudget = "names more strip, tile or thumbnail values than its data holds";
+
+ ///
+ /// Strip, tile and thumbnail offset/length tags (TIFF 6.0 §3, tags 0x0111/0x0117, 0x0144/0x0145, and
+ /// JPEGInterchangeFormat 0x0201/0x0202) are plain only as SHORT (3) or LONG (4), and only when each array lies
+ /// wholly in the data and is named once. A complete pair whose values, counted from the entry headers, exceed
+ /// half the bytes is not plain. A next-IFD field that is partly in the data is not plain. The first entry exiftool will see is
+ /// plain only when does not change; GPS tables are not edited.
+ ///
+ public static Verdict Judge (TiffReader tiff, IfdGraph graph, HashSet tags)
+ {
+ string? why = null;
+ var removes = false;
+ long budget = 0;
+ HashSet? named = null;
+ HashSet? counted = null;
+ var slots = new ValueArray[6];
+ for (var t = 0; t < graph.Tables.Count; t++) {
+ var (at, count, roles) = graph.Tables[t];
+ why ??= NextFieldCutShort (tiff, at, count);
+ var notes = NoteEntries (tiff, at, count, (roles & IfdGraph.ReadRoles) != 0, tags, slots, ref named, ref why);
+ removes |= notes.Removes;
+ if (why is null)
+ budget += CompletePairCounts (slots, notes.Got, ref counted);
+ why ??= FirstEntryReadability (count, notes);
+ if (why is not null && removes)
+ break;
+ }
+
+ // Counts come from the entry headers. The first reason stands: a cut-short next field, a pair tag given
+ // twice, a type other than SHORT or LONG, an array that does not fit, one array named twice, then a first
+ // entry whose readability would change. The budget is reported only when none of those was found.
+ if (why is null && removes && ValueBudget.PastHalf (0, budget, tiff.Length))
+ why = OverBudget;
+ return new Verdict (why is null, removes, why);
+ }
+
+ // Entry(at, count) is the first byte after the entries: the classic 4-byte next-IFD field.
+ static string? NextFieldCutShort (TiffReader tiff, long at, int count)
+ {
+ var nextAt = tiff.Entry (at, count);
+ return nextAt < tiff.Length && nextAt + 4 > tiff.Length ? NextCutShort : null;
+ }
+
+ static TableNotes NoteEntries (
+ TiffReader tiff,
+ long at,
+ int count,
+ bool edited,
+ HashSet tags,
+ ValueArray[] slots,
+ ref HashSet? named,
+ ref string? why)
+ {
+ var notes = new TableNotes ();
+ var seenSide = 0;
+ for (var n = 0; n < count; n++) {
+ IfdSteps.Count++;
+ var entry = tiff.Entry (at, n);
+ var tag = tiff.Tag (entry);
+ if (n == 0)
+ notes.FirstType = tiff.Type (entry);
+ if (edited && tags.Contains (tag)) {
+ notes.Removes = true;
+ notes.Loses = true;
+ } else if (!notes.KeptOne) {
+ notes.KeptOne = true;
+ notes.KeptType = tiff.Type (entry);
+ }
+
+ // Once a reason stands it is kept, and later entries are not read for another one.
+ if (why is null)
+ why = PairEntry (tiff, entry, tag, ref seenSide, ref notes, slots, ref named);
+ }
+
+ return notes;
+ }
+
+ // A second entry with the same pair tag names a different array. Which bytes it means is unknown.
+ static string? PairEntry (
+ TiffReader tiff,
+ long entry,
+ int tag,
+ ref int seenSide,
+ ref TableNotes notes,
+ ValueArray[] slots,
+ ref HashSet? named)
+ {
+ var slot = OffsetLengthPairs.Slot (tag);
+ if (slot < 0)
+ return null;
+ var repeated = (seenSide & (1 << slot)) != 0;
+ seenSide |= 1 << slot;
+ if (tiff.Count (entry) == 0 || repeated)
+ return repeated ? PairTagRepeated : null;
+ if (tiff.Type (entry) is not (3 or 4))
+ return PairTypeWrong;
+ if (!tiff.TryValueArray (entry, out var key))
+ return PairDoesNotFit;
+ named ??= [];
+ if (!named.Add (key))
+ return PairArrayRepeated;
+ slots[slot] = key;
+ notes.Got |= 1 << slot;
+ return null;
+ }
+
+ // Both sides of a pair, from this table's headers. A lone offset or length is not a value the plan reads.
+ static long CompletePairCounts (ValueArray[] slots, int got, ref HashSet? counted)
+ {
+ if (got == 0)
+ return 0;
+ long added = 0;
+ for (var pair = 0; pair < 6; pair += 2) {
+ if ((got & (3 << pair)) != (3 << pair))
+ continue;
+ counted ??= [];
+ if (counted.Add (slots[pair]))
+ added += slots[pair].Count;
+ if (counted.Add (slots[pair + 1]))
+ added += slots[pair + 1].Count;
+ }
+
+ return added;
+ }
+
+ // An empty table is read. A table with entries is read when its first format is one exiftool reads.
+ static string? FirstEntryReadability (int count, TableNotes notes)
+ {
+ if (!notes.Loses)
+ return null;
+ var before = count == 0 || TiffReader.FormatExiftoolReads (notes.FirstType);
+ var after = !notes.KeptOne || TiffReader.FormatExiftoolReads (notes.KeptType);
+ return before != after ? FirstEntryChanges : null;
+ }
+
+ struct TableNotes
+ {
+ public bool Removes;
+ public bool Loses;
+ public int FirstType;
+ public int KeptType;
+ public bool KeptOne;
+ public int Got;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Exif/RemovalPlan.cs b/src/TagLibSharp2/Image/Exif/RemovalPlan.cs
new file mode 100644
index 00000000..785ac139
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/RemovalPlan.cs
@@ -0,0 +1,409 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image.Exif;
+
+///
+/// What an Exif removal changes: the entries to remove from each table, the values they free, and the bytes that
+/// must never be zeroed.
+///
+///
+/// Never zeroed: the header (a value is cleared only from byte 8), every table (count, entries, next offset), every
+/// kept entry's value (a SubIFD offset array is the value of the 0x014A entry that names it, which is never
+/// removed), the data that offset/length pairs name (the IFD1 thumbnail, strips, tiles), the structure of every
+/// table no reader reads (its count, entries and next offset as far as the data goes), and the bytes a maker note
+/// (Exif 2.32 §4.6.5 tag 0x927C) or one of its entries names. A removed value inside the note's own block still
+/// overlaps that kept value, so the edit is refused. A value the note's entries name past the block is kept and
+/// the edit runs: zeroing it would change the note, and refusing would reject a plain file. A maker note whose
+/// IFD this pass does not finish (a version byte, a rejected entry, an unknown layout, or the entry budget)
+/// leaves every removed value outside the tables as it was.
+///
+sealed class RemovalPlan
+{
+ // Exif 2.32 §4.6.5. The block is undefined; a classic IFD in it is the note's own directory.
+ const int MakerNoteTag = 0x927C;
+ const int MakerNotePrefix = 32;
+
+ public CountedList<(long Start, long End)> Protected { get; } = new ();
+ public CountedList<(long Start, long End)> Removed { get; } = new ();
+
+ ///
+ /// The kept entries' values and the data their offset/length pairs name, in tables some reader reads and wholly
+ /// inside the data (a value past the data is read by no one: exiftool reports a bad offset), with the tag that
+ /// names each.
+ ///
+ public CountedList<(long Start, long End, int Tag)> Kept { get; } = new ();
+
+ /// For each table that loses an entry, which of its entries go.
+ public Dictionary> Removing { get; } = new ();
+
+ ///
+ /// The offset and length arrays name more values, across every table, than half the bytes of the block. The
+ /// plan then does not hold every range, so an edit that has something to remove is refused rather than applied.
+ /// The plainness check refuses the same bound from the entry headers first. This stop remains so a caller that
+ /// skips that check neither allocates past the bound nor applies a partial plan. The comparison is
+ /// .
+ ///
+ public bool ValueBudgetExceeded { get; private set; }
+
+ // Each distinct SHORT or LONG array once. Keyed as a pointer array is: where it starts, how many values, and
+ // how wide each value is. A plain edit names each array once; the cache still keeps a skipped check from
+ // reading one array twice.
+ readonly Dictionary _values = new ();
+ long _valuesRead;
+
+ // The maker-note block and the values its entries name. Apply skips these bytes. They are not protected:
+ // a share with them is not a reason to refuse.
+ readonly CountedList<(long Start, long End)> _makerOwned = new ();
+
+ // False when any UNDEFINED maker note was not walked to the end: a version byte, a rejected entry, an
+ // unknown layout, or the entry budget. Zeroing then leaves removed values outside the tables as they are.
+ bool _allNotesLocated = true;
+
+ // Entry reads across every maker note. One note fits: its entries occupy twelve bytes each. A second walk of
+ // the same bytes, or of a blob that overlaps one already walked, stops at the size of the block.
+ long _noteBudget;
+ long _noteEntriesRead;
+
+ bool NoteBudgetSpent => _noteEntriesRead >= _noteBudget;
+
+ // The outside targets of a blob already walked, or null when that walk did not locate the IFD.
+ readonly Dictionary<(long Start, long End), CountedList<(long Start, long End)>?> _noteScans = new ();
+
+ public static RemovalPlan Mark (TiffReader tiff, IfdGraph graph, HashSet tags)
+ {
+ var plan = new RemovalPlan { _noteBudget = tiff.Length };
+ for (var t = 0; t < graph.Tables.Count; t++) {
+ var (at, count, roles) = graph.Tables[t];
+ var seen = (roles & IfdGraph.SeenRoles) != 0;
+ var table = TiffReader.TableRange (at, count);
+ plan.Protected.Add (table);
+ plan.AddDataRanges (tiff, at, count, seen);
+ plan.MarkEntries (tiff, at, count, edited: (roles & IfdGraph.ReadRoles) != 0, seen, tags);
+ }
+
+ for (var n = 0; n < graph.Unread.Count; n++) {
+ var at = graph.Unread[n];
+ var entries = at + 2 <= tiff.Length ? tiff.U16 (at) : 0;
+ var unread = (at, Math.Min (at + 2 + (entries * 12L) + 4, tiff.Length));
+ plan.Protected.Add (unread);
+ }
+
+ return plan;
+ }
+
+ // Every kept value is protected. The out-of-line value of an Exif, GPS or interoperability IFD pointer (count 2,
+ // or a wide type) is shown by no reader (exiftool: "Bad value"); what it leads to is a table.
+ void MarkEntries (TiffReader tiff, long at, int count, bool edited, bool seen, HashSet tags)
+ {
+ for (var n = 0; n < count; n++) {
+ IfdSteps.Count++;
+ var entry = tiff.Entry (at, n);
+ var range = tiff.ValueRange (entry);
+ if (edited && tags.Contains (tiff.Tag (entry))) {
+ if (!Removing.TryGetValue (at, out var marks))
+ Removing[at] = marks = CountedList.Filled (count);
+ marks[n] = true;
+ if (range.End > range.Start)
+ Removed.Add (range);
+ } else if (range.End > range.Start) {
+ Protected.Add (range);
+ if (seen && tiff.Tag (entry) is not (TiffReader.ExifIfdPointer or TiffReader.GpsIfdPointer or TiffReader.InteropIfdPointer)
+ && range.Start < tiff.Length && range.End <= tiff.Length)
+ Kept.Add ((range.Start, range.End, tiff.Tag (entry)));
+ if (tiff.Tag (entry) == MakerNoteTag && tiff.Type (entry) == 7)
+ RecordMakerNote (tiff, range);
+ }
+ }
+ }
+
+ ///
+ /// Whether zeroing the removed values would leave every protected byte alone. Two protected ranges may share a
+ /// byte: that share is not zeroed. A table being compacted is a separate question, answered where the edit is
+ /// applied. A pair tag given twice is not this question: the plainness check owns it.
+ ///
+ public bool IsClean ()
+ {
+ if (ValueBudgetExceeded)
+ return false;
+ if (Removed.Count == 0 || Protected.Count == 0)
+ return true;
+ var guarded = new CountedList<(long Start, long End)> ();
+ for (var n = 0; n < Protected.Count; n++)
+ guarded.Add (Protected[n]);
+ var merged = ByteRanges.Merge (guarded);
+ for (var n = 0; n < Removed.Count; n++) {
+ if (ByteRanges.Overlaps (merged, Removed[n]))
+ return false;
+ }
+
+ return true;
+ }
+
+ /// Compacts every table that loses an entry, then zeroes the freed values no other structure uses.
+ public void Apply (Span data, TiffReader tiff, IfdGraph graph)
+ {
+ for (var t = 0; t < graph.Tables.Count; t++) {
+ var (at, count, _) = graph.Tables[t];
+ if (Removing.TryGetValue (at, out var marks))
+ CompactTable (data, tiff, at, count, marks);
+ }
+
+ // One sort, then a binary search per removed value: linear-logarithmic in the entries, whatever their number.
+ var merged = ByteRanges.Merge (Protected);
+ var maker = ByteRanges.Merge (_makerOwned);
+ for (var n = 0; n < Removed.Count; n++) {
+ var range = Removed[n];
+ if (range.Start < TiffReader.HeaderSize || range.End > data.Length || ByteRanges.Overlaps (merged, range))
+ continue;
+ // A note this pass did not finish may name any byte outside the tables. A value inside a table
+ // overlaps Protected and was skipped above, so every range here is outside them.
+ if (!_allNotesLocated)
+ continue;
+ ClearExcept (data, range, maker);
+ }
+ }
+
+ // Zeroes [range) except where a maker-note range covers it. Both lists are sorted and disjoint, so the covered
+ // part is one forward pass from the first note range that ends after the value starts.
+ static void ClearExcept (Span data, (long Start, long End) range, CountedList<(long Start, long End)> maker)
+ {
+ var cursor = range.Start;
+ var low = ByteRanges.FirstEndingAfter (maker, range.Start);
+
+ for (var n = low; n < maker.Count; n++) {
+ var keep = maker[n];
+ if (keep.Start >= range.End)
+ break;
+ var keepStart = Math.Max (keep.Start, range.Start);
+ var keepEnd = Math.Min (keep.End, range.End);
+ if (cursor < keepStart)
+ data.Slice ((int)cursor, (int)(keepStart - cursor)).Clear ();
+ if (keepEnd > cursor)
+ cursor = keepEnd;
+ }
+
+ if (cursor < range.End)
+ data.Slice ((int)cursor, (int)(range.End - cursor)).Clear ();
+ }
+
+ // The note's own bytes, then any value a classic IFD in the note names outside that block. The IFD may sit at
+ // the start or after at most 32 bytes of ASCII or NUL (Panasonic's "Panasonic" header is 12). One pass over
+ // the entries. Offsets that all land inside the block are counted from the block, so nothing outside it is
+ // claimed. Offsets that all land inside the TIFF are counted from the TIFF, and only those outside the block
+ // are kept as well. A mix that fits neither is left to the block alone.
+ void RecordMakerNote (TiffReader tiff, (long Start, long End) blob)
+ {
+ var end = Math.Min (blob.End, tiff.Length);
+ if (blob.Start < 0 || end <= blob.Start)
+ return;
+ _makerOwned.Add ((blob.Start, end));
+ var key = (blob.Start, end);
+ // The first walk already stored this blob's outside ranges. Copying them again is the square of the notes.
+ if (_noteScans.TryGetValue (key, out var cached)) {
+ if (cached is null)
+ _allNotesLocated = false;
+ return;
+ }
+
+ if (NoteBudgetSpent || !TryMakerTargets (tiff, blob.Start, end, out var outside)) {
+ _allNotesLocated = false;
+ _noteScans[key] = null;
+ return;
+ }
+
+ _noteScans[key] = outside;
+ CopyRanges (outside);
+ }
+
+ void CopyRanges (CountedList<(long Start, long End)> ranges)
+ {
+ for (var n = 0; n < ranges.Count; n++)
+ _makerOwned.Add (ranges[n]);
+ }
+
+ bool TryMakerTargets (TiffReader tiff, long blobStart, long blobEnd, out CountedList<(long Start, long End)> outside)
+ {
+ outside = new CountedList<(long Start, long End)> ();
+ var last = blobStart + MakerNotePrefix;
+ for (var at = blobStart; at + 2 <= blobEnd && at <= last; at++) {
+ if (TryNoteIfd (tiff, at, blobStart, blobEnd, out outside))
+ return true;
+ if (NoteBudgetSpent)
+ return false;
+ if (at < 0 || at >= tiff.Length || !IsAsciiOrNul (tiff.Data[(int)at]))
+ break;
+ }
+
+ return false;
+ }
+
+ // A classic IFD wholly inside the block: a count, sorted tags, types 1-12 (TIFF 6.0 §2). False leaves
+ // unused.
+ bool TryNoteIfd (
+ TiffReader tiff,
+ long at,
+ long blobStart,
+ long blobEnd,
+ out CountedList<(long Start, long End)> outside)
+ {
+ outside = new CountedList<(long Start, long End)> ();
+ if (at < 0 || at > tiff.Length - 2)
+ return false;
+ var count = tiff.U16 (at);
+ if (count <= 0)
+ return false;
+ var tableEnd = at + 2 + (count * 12L) + 4;
+ if (tableEnd < at || tableEnd > blobEnd)
+ return false;
+ var fromNote = true;
+ var fromTiff = true;
+ var extra = new CountedList<(long Start, long End)> ();
+ long previous = -1;
+ for (var n = 0; n < count; n++) {
+ if (NoteBudgetSpent)
+ return false;
+
+ _noteEntriesRead++;
+ IfdSteps.Count++;
+ var entry = tiff.Entry (at, n);
+ var tag = tiff.Tag (entry);
+ var type = tiff.Type (entry);
+ if (tag <= previous || type is < 1 or > 12)
+ return false;
+ previous = tag;
+ var range = tiff.ValueRange (entry);
+ var size = range.End - range.Start;
+ if (size <= 0)
+ continue;
+ var offset = range.Start;
+ var inNote = Fits (blobStart, offset, size, blobEnd);
+ var inTiff = Fits (0, offset, size, tiff.Length);
+ if (!inNote)
+ fromNote = false;
+ // A value past the TIFF is not part of this block. One inside the TIFF but outside the note is.
+ if ((inTiff || offset < tiff.Length) && !WhollyInside (offset, size, blobStart, blobEnd))
+ extra.Add ((offset, offset + size));
+ if (!inTiff)
+ fromTiff = false;
+ // A count taken from a version byte can look like an IFD. Past the first byte, a value that fits
+ // neither the note nor the TIFF is not that IFD.
+ if (at > blobStart && !inNote && !inTiff)
+ return false;
+ }
+
+ if (!fromNote && fromTiff)
+ outside = extra;
+ return true;
+ }
+
+ static bool Fits (long origin, long offset, long size, long limit)
+ {
+ if (offset < 0 || size <= 0 || origin > long.MaxValue - offset)
+ return false;
+ var start = origin + offset;
+ return start <= limit && size <= limit - start;
+ }
+
+ static bool WhollyInside (long start, long size, long low, long high) =>
+ start >= low && start <= high && size <= high - start;
+
+ static bool IsAsciiOrNul (byte value) => value == 0 || value is >= 0x20 and <= 0x7E;
+
+ // Moves the kept entries up and the next-IFD offset after them (0 when it was missing or cut short), then clears
+ // the freed bytes up to the end of the old offset, or of the data when the table ended there.
+ static void CompactTable (Span data, TiffReader tiff, long ifd, int count, CountedList removing)
+ {
+ var at = (int)ifd;
+ var table = at + 2;
+ var kept = 0;
+ for (var n = 0; n < count; n++) {
+ if (removing[n])
+ continue;
+ if (kept != n)
+ data.Slice (table + (n * 12), 12).CopyTo (data.Slice (table + (kept * 12)));
+ kept++;
+ }
+
+ var nextAt = table + (count * 12);
+ var next = nextAt + 4 <= data.Length ? Endian.U32 (data, nextAt, tiff.LittleEndian) : 0;
+ Endian.WriteU16 (data, at, kept, tiff.LittleEndian);
+ var newNext = table + (kept * 12);
+ Endian.WriteU32 (data, newNext, next, tiff.LittleEndian);
+ data.Slice (newNext + 4, Math.Min (nextAt + 4, data.Length) - (newNext + 4)).Clear ();
+ }
+
+ // Each array is read once. Values read across every table are bounded by half the bytes present: two arrays that
+ // both fit can pass that only by overlapping, and past it the plan stops reading rather than allocating. A plain
+ // edit never reaches that bound; it is refused from the entry headers first. A second entry with the same pair
+ // tag is the plainness check's reason, so the first entry is the one read here.
+ void AddDataRanges (TiffReader tiff, long ifd, int count, bool seen)
+ {
+ foreach (var (offsetsTag, lengthsTag) in OffsetLengthPairs.All) {
+ var hasOffsets = TryKey (tiff, ifd, count, offsetsTag, out var offsetsKey);
+ var hasLengths = TryKey (tiff, ifd, count, lengthsTag, out var lengthsKey);
+ if (!hasOffsets || !hasLengths || ValueBudgetExceeded)
+ continue;
+ if (!TryValues (tiff, offsetsKey, out var offsets) || !TryValues (tiff, lengthsKey, out var lengths))
+ continue;
+ var shared = Math.Min (offsets.Length, lengths.Length);
+ for (var n = 0; n < shared; n++) {
+ var end = offsets[n] + lengths[n];
+ if (end < offsets[n])
+ continue;
+ Protected.Add ((offsets[n], end));
+ if (seen && offsets[n] < tiff.Length && end <= tiff.Length)
+ Kept.Add ((offsets[n], end, offsetsTag));
+ }
+ }
+ }
+
+ // The first SHORT or LONG entry with the tag, when every value lies in the data.
+ static bool TryKey (TiffReader tiff, long ifd, int count, int tag, out ValueArray key)
+ {
+ key = default;
+ var found = FindEntry (tiff, ifd, count, tag);
+ return found >= 0 && tiff.TryValueArray (tiff.Entry (ifd, found), out key);
+ }
+
+ // The values of one array, from the cache when a table already named it. Past the bound, or a count no array
+ // can hold, nothing is allocated and the plan is incomplete.
+ bool TryValues (TiffReader tiff, ValueArray key, out long[] values)
+ {
+ if (_values.TryGetValue (key, out var cached)) {
+ values = cached;
+ return true;
+ }
+ if (key.Count > int.MaxValue || ValueBudget.PastHalf (_valuesRead, key.Count, tiff.Length)) {
+ ValueBudgetExceeded = true;
+ values = [];
+ return false;
+ }
+
+ var count = (int)key.Count;
+ values = new long[count];
+ for (var k = 0; k < count; k++) {
+ IfdSteps.Count++;
+ var p = (int)key.At + (k * key.Size);
+ values[k] = key.Size == 2 ? tiff.U16 (p) : tiff.U32 (p);
+ }
+
+ _valuesRead += count;
+ _values[key] = values;
+ return true;
+ }
+
+ // The first entry with the tag, or -1. A second entry with that tag is refused by the plainness check.
+ static int FindEntry (TiffReader tiff, long ifd, int count, int tag)
+ {
+ for (var n = 0; n < count; n++) {
+ IfdSteps.Count++;
+ if (tiff.Tag (tiff.Entry (ifd, n)) == tag)
+ return n;
+ }
+
+ return -1;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Exif/ValueBudget.cs b/src/TagLibSharp2/Image/Exif/ValueBudget.cs
new file mode 100644
index 00000000..04e51989
--- /dev/null
+++ b/src/TagLibSharp2/Image/Exif/ValueBudget.cs
@@ -0,0 +1,15 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+namespace TagLibSharp2.Image.Exif;
+
+///
+/// Whether offset and length arrays name more values than half the bytes. Equality still fits: two arrays that
+/// both lie in the data can meet it. The plainness check counts from the entry headers and the removal plan counts
+/// the values it is about to read. Both ask here. The plan keeps its own stop, because a test may skip the
+/// plainness check: that stop is what the edit matrix counts, and it is what keeps the plan from allocating past it.
+///
+static class ValueBudget
+{
+ public static bool PastHalf (long already, long more, long length) => more > (length / 2) - already;
+}
diff --git a/src/TagLibSharp2/Image/Gif/GifRewriter.cs b/src/TagLibSharp2/Image/Gif/GifRewriter.cs
new file mode 100644
index 00000000..0f34c6be
--- /dev/null
+++ b/src/TagLibSharp2/Image/Gif/GifRewriter.cs
@@ -0,0 +1,329 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Text;
+using TagLibSharp2.Core;
+using TagLibSharp2.Image.Xmp;
+
+namespace TagLibSharp2.Image.Gif;
+
+///
+/// Reads a GIF's comment extensions and splices a new one after the header (GIF89a §24). Every other block, and
+/// anything after the trailer, is copied as it is; the XMP copy of a changed comment is updated.
+///
+static class GifRewriter
+{
+ internal const string HeaderError = "The GIF header is truncated, so the comment cannot be spliced in.";
+ internal const string SpliceError =
+ "The GIF block list is truncated or holds an unknown block, so the comment cannot be spliced in.";
+
+ public static void Read (ReadOnlySpan data, ImageTag tag)
+ {
+ if (TryComments (data, out var text))
+ tag.ReadField (ImageStores.Comment, text);
+ }
+
+ /// The edited file as new pieces and ranges of .
+ public static ImagePlan? Plan (ReadOnlySpan data, ImageTag tag, out string? error)
+ {
+ error = null;
+ var replaceComment = tag.Changed (ImageStores.Comment);
+ if (!replaceComment && !tag.DropUnmapped)
+ return null;
+ if (!TryHeader (data, out var header)) {
+ error = HeaderError;
+ return null;
+ }
+
+ var plan = new ImagePlan ();
+ var comment = replaceComment ? tag.Field (ImageStores.Comment) : null;
+ if (comment is not null && data.StartsWith ("GIF87a"u8)) {
+ plan.Add ("GIF89a"u8);
+ plan.Copy (6, header - 6);
+ } else {
+ plan.Copy (0, header);
+ }
+
+ if (comment is not null)
+ plan.Add (CommentBytes (comment));
+ if (TryCopyBlocks (data, header, tag, replaceComment, plan, out error))
+ return plan;
+ error ??= SpliceError;
+ return null;
+ }
+
+ static byte[] CommentBytes (string comment)
+ {
+ using var builder = new BinaryDataBuilder ();
+ AddComment (builder, comment);
+ return builder.ToArray ();
+ }
+
+ // Copies the blocks after the header through the trailer and what follows it. False at a truncated or unknown
+ // block (error null), or when the XMP copy cannot be updated (error set).
+ static bool TryCopyBlocks (
+ ReadOnlySpan data,
+ int header,
+ ImageTag tag,
+ bool replaceComment,
+ ImagePlan plan,
+ out string? error)
+ {
+ error = null;
+ var mirrors = replaceComment && !tag.DropUnmapped;
+ var i = header;
+ while (i < data.Length) {
+ var start = i;
+ var introducer = data[i];
+ if (introducer == 0x3B) {
+ plan.Copy (start, data.Length - start);
+ return true;
+ }
+
+ if (introducer == 0x2C) {
+ if (!SkipImage (data, ref i))
+ return false;
+ plan.Copy (start, i - start);
+ continue;
+ }
+
+ if (introducer != 0x21 || i + 2 > data.Length || !SkipSubBlocks (data, ref i, startAtLabel: true))
+ return false;
+ if (!TryCopyExtension (data, start, i - start, tag, replaceComment, mirrors, plan, out error))
+ return false;
+ }
+
+ return false;
+ }
+
+ static bool TryCopyExtension (
+ ReadOnlySpan data,
+ int start,
+ int length,
+ ImageTag tag,
+ bool replaceComment,
+ bool mirrors,
+ ImagePlan plan,
+ out string? error)
+ {
+ error = null;
+ var block = data.Slice (start, length);
+ if ((replaceComment && block[1] == 0xFE) || (tag.DropUnmapped && !IsKeptOnClear (block)))
+ return true;
+ if (!mirrors || !IsXmp (block)) {
+ plan.Copy (start, length);
+ return true;
+ }
+
+ if (!TryMirrorXmp (block, tag, out var edited, out error))
+ return false;
+ if (edited is not null)
+ plan.Add (edited);
+ else
+ plan.Copy (start, length);
+ return true;
+ }
+
+ // GIF89a defines four extensions: graphic control (0xF9), plain text (0x01), comment (0xFE) and
+ // application (0xFF). Clear keeps graphic control and plain text (they are drawn), and the application
+ // extensions a decoder or colour management needs: NETSCAPE2.0 and ANIMEXTS1.0 (the loop count) and
+ // ICCRGBG1012 (the ICC profile). Every other application extension (XMP, ImageMagick's IPTC and 8BIM, and
+ // unknown ones) and any extension with an undefined label is dropped; the comment goes through the tag.
+ static bool IsKeptOnClear (ReadOnlySpan block)
+ {
+ var label = block[1];
+ if (label is 0xF9 or 0x01 or 0xFE)
+ return true;
+ if (label != 0xFF || block.Length < 14 || block[2] != 11)
+ return false;
+ var id = block.Slice (3, 11);
+ return id.SequenceEqual ("NETSCAPE2.0"u8) || id.SequenceEqual ("ANIMEXTS1.0"u8) || id.SequenceEqual ("ICCRGBG1012"u8);
+ }
+
+ static bool IsXmp (ReadOnlySpan block) =>
+ block.Length >= 14 && block[1] == 0xFF && block[2] == 11 && block.Slice (3, 11).SequenceEqual ("XMP DataXMP"u8);
+
+ // XMP Specification Part 3 §1.1.2: the GIF XMP extension holds the packet bytes as they are, then a
+ // 258-byte "magic trailer" (0x01, 0xFF down to 0x00, then 0x00) that makes the bytes parse as sub-blocks.
+ static byte[] XmpTrailer ()
+ {
+ var trailer = new byte[258];
+ trailer[0] = 0x01;
+ for (var n = 0; n < 256; n++)
+ trailer[1 + n] = (byte)(0xFF - n);
+ return trailer;
+ }
+
+ static bool TryMirrorXmp (ReadOnlySpan block, ImageTag tag, out byte[]? edited, out string? error)
+ {
+ edited = null;
+ error = null;
+ var trailer = XmpTrailer ();
+ if (block.Length < 14 + trailer.Length || !block.Slice (block.Length - trailer.Length).SequenceEqual (trailer))
+ return TryMirrorXmpSubBlocks (block, tag, out edited, out error);
+
+ var packet = Encoding.UTF8.GetString (block.Slice (14, block.Length - 14 - trailer.Length));
+ if (!XmpMirror.TryUpdate (packet, tag, "GIF XMP packet", out var updated, out error))
+ return false;
+ if (ReferenceEquals (updated, packet))
+ return true;
+ var bytes = Encoding.UTF8.GetBytes (updated);
+ edited = new byte[14 + bytes.Length + trailer.Length];
+ block.Slice (0, 14).CopyTo (edited);
+ bytes.CopyTo (edited, 14);
+ trailer.CopyTo (edited, 14 + bytes.Length);
+ return true;
+ }
+
+ // ImageIO writes the GIF XMP packet as ordinary data sub-blocks (GIF89a §15) instead of the raw bytes and the
+ // magic trailer. The packet is then the sub-blocks joined, and is written back the same way.
+ static bool TryMirrorXmpSubBlocks (ReadOnlySpan block, ImageTag tag, out byte[]? edited, out string? error)
+ {
+ edited = null;
+ error = null;
+ var joined = JoinSubBlocks (block, out var end);
+ if (end != block.Length - 1 || !joined.Contains ((byte)'<')) {
+ if (block.IndexOf ("UserComment"u8) < 0)
+ return true;
+ error = "The GIF XMP extension is neither the XMP raw form with its magic trailer nor data sub-blocks, and holds a UserComment, so that copy of Comment cannot be located and updated.";
+ return false;
+ }
+
+ var packet = Encoding.UTF8.GetString ([.. joined]);
+ if (!XmpMirror.TryUpdate (packet, tag, "GIF XMP packet", out var updated, out error))
+ return false;
+ if (ReferenceEquals (updated, packet))
+ return true;
+ using var builder = new BinaryDataBuilder (block.Length + 64);
+ builder.Add (block.Slice (0, 14));
+ var bytes = Encoding.UTF8.GetBytes (updated);
+ for (var at = 0; at < bytes.Length; at += 255) {
+ var take = Math.Min (255, bytes.Length - at);
+ builder.Add ((byte)take);
+ builder.Add (bytes.AsSpan (at, take));
+ }
+
+ builder.Add (0);
+ edited = builder.ToArray ();
+ return true;
+ }
+
+ // The data of the sub-blocks after the 14-byte application header, and where the walk stopped.
+ static List JoinSubBlocks (ReadOnlySpan block, out int end)
+ {
+ var joined = new List (block.Length);
+ var i = 14;
+ while (i < block.Length && block[i] != 0) {
+ var size = block[i];
+ if (i + 1 + size > block.Length)
+ break;
+ for (var n = 0; n < size; n++)
+ joined.Add (block[i + 1 + n]);
+ i += 1 + size;
+ }
+
+ end = i;
+ return joined;
+ }
+
+ static bool TryComments (ReadOnlySpan data, out string? text)
+ {
+ text = null;
+ if (!TryHeader (data, out var header))
+ return false;
+ var collected = new List ();
+ var i = header;
+ while (i < data.Length) {
+ var introducer = data[i];
+ if (introducer == 0x3B) {
+ text = collected.Count == 0 ? null : Encoding.UTF8.GetString (collected.ToArray ());
+ return true;
+ }
+
+ var skipped = introducer switch {
+ 0x21 => i + 2 <= data.Length && SkipSubBlocks (data, ref i, startAtLabel: true, data[i + 1] == 0xFE ? collected : null),
+ 0x2C => SkipImage (data, ref i),
+ _ => false
+ };
+ if (!skipped)
+ return false;
+ }
+
+ return false;
+ }
+
+ static bool TryHeader (ReadOnlySpan data, out int header)
+ {
+ header = 0;
+ if (data.Length < 13 || (!data.StartsWith ("GIF87a"u8) && !data.StartsWith ("GIF89a"u8)))
+ return false;
+ var colors = (data[10] & 0x80) == 0 ? 0 : 3 * (1 << ((data[10] & 0x07) + 1));
+ header = 13 + colors;
+ return header <= data.Length;
+ }
+
+ static bool SkipImage (ReadOnlySpan data, ref int i)
+ {
+ if (i + 10 > data.Length)
+ return false;
+ var packed = data[i + 9];
+ i += 10;
+ if ((packed & 0x80) != 0) {
+ var table = 3 * (1 << ((packed & 0x07) + 1));
+ if (i + table > data.Length)
+ return false;
+ i += table;
+ }
+
+ if (i >= data.Length)
+ return false;
+ i++;
+ return SkipSubBlocks (data, ref i, startAtLabel: false);
+ }
+
+ static bool SkipSubBlocks (ReadOnlySpan data, ref int i, bool startAtLabel, List? payload = null)
+ {
+ if (startAtLabel) {
+ if (i + 2 > data.Length)
+ return false;
+ i += 2;
+ }
+
+ while (i < data.Length) {
+ var size = data[i++];
+ if (size == 0)
+ return true;
+ if (i + size > data.Length)
+ return false;
+ if (payload is not null) {
+ for (var n = 0; n < size; n++)
+ payload.Add (data[i + n]);
+ }
+
+ i += size;
+ }
+
+ return false;
+ }
+
+ /// A comment extension (GIF89a §24): sub-blocks of at most 255 bytes, split between UTF-8 sequences.
+ public static void AddComment (BinaryDataBuilder builder, string comment)
+ {
+ var bytes = Encoding.UTF8.GetBytes (comment);
+ builder.Add (0x21);
+ builder.Add (0xFE);
+ var offset = 0;
+ while (offset < bytes.Length) {
+ var take = Math.Min (255, bytes.Length - offset);
+ while (take > 0 && offset + take < bytes.Length && (bytes[offset + take] & 0xC0) == 0x80)
+ take--;
+ if (take == 0)
+ take = Math.Min (255, bytes.Length - offset);
+ builder.Add ((byte)take);
+ builder.Add (bytes.AsSpan (offset, take));
+ offset += take;
+ }
+
+ builder.Add (0);
+ }
+}
diff --git a/src/TagLibSharp2/Image/ImageGainMap.cs b/src/TagLibSharp2/Image/ImageGainMap.cs
new file mode 100644
index 00000000..d5970ee2
--- /dev/null
+++ b/src/TagLibSharp2/Image/ImageGainMap.cs
@@ -0,0 +1,506 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Globalization;
+using System.Text;
+using System.Xml;
+
+namespace TagLibSharp2.Image;
+
+///
+/// The XMP an HDR decoder needs to find and apply a JPEG gain map, which Clear keeps (rule 7: what a decoder
+/// needs). Clear writes a new packet from an explicit list of properties with typed values; nothing of the
+/// original packet is copied, so no other property, attribute, nested structure, comment or text survives.
+///
+///
+/// Ultra HDR v1.0 (https://developer.android.com/media/platform/hdr-image-format, "XMP attributes"):
+/// hdrgm:Version ("1.0"), hdrgm:BaseRenditionIsHDR (Boolean), hdrgm:GainMapMin,
+/// GainMapMax, Gamma, OffsetSDR, OffsetHDR (Real, or an ordered array of three Reals,
+/// one per channel), hdrgm:HDRCapacityMin and HDRCapacityMax (Real); and in the primary image,
+/// Container:Directory, an ordered array of Container:Item structures with Item:Semantic,
+/// Item:Mime, Item:Length and Item:Padding (lengths and paddings are integers; an item's
+/// offset is the primary's length plus the preceding items' lengths and paddings).
+/// Apple (the properties ImageIO writes for an HDRGainMap auxiliary image, as in
+/// CGImageDestinationAddAuxiliaryDataInfo output): apdi:AuxiliaryImageType
+/// (urn:com:apple:photo:2020:aux:hdrgainmap), apdi:NativeFormat and apdi:StoredFormat
+/// (integer pixel formats), HDRGainMap:HDRGainMapVersion (integer) and, from version 131072 (iPhone 15),
+/// HDRGainMap:HDRGainMapHeadroom (Real), the headroom ImageIO and libultrahdr scale the gain map by. A
+/// version-65536 gain map (iPhone 12-14) has no headroom in its XMP: decoders compute it from the primary image's
+/// Apple maker note, tags 33 and 48 (Apple, "Applying Apple HDR effect to your photos",
+/// https://developer.apple.com/documentation/appkit/applying-apple-hdr-effect-to-your-photos). For such a packet
+/// Clear keeps those two values, as ImageIO applies them, and nothing else of the Exif, in a new minimal Exif in
+/// the primary (, which also says why it is not a conformant Exif);
+/// after Clear ImageIO decodes the HDR rendition exactly as before. Without them ImageIO renders the photo SDR and
+/// libultrahdr refuses it as a gain-map image.
+/// Motion Photo 1.0 (https://developer.android.com/media/platform/motion-photo-format): Camera:MotionPhoto
+/// and Camera:MotionPhotoVersion (Integer) and Camera:MotionPhotoPresentationTimestampUs (Long, -1 for
+/// unset), and the directory's Item:Semantic and Item:Mime values, which are enumerated.
+/// The packet is read with one forward pass of that keeps only the path of the
+/// current element, so the cost is linear in the packet and nesting does not recurse. Only properties of a
+/// top-level rdf:Description count; the first occurrence of a property wins.
+///
+static class ImageGainMap
+{
+ const string Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+ const string Hdrgm = "http://ns.adobe.com/hdr-gain-map/1.0/";
+ const string AppleGainMap = "http://ns.apple.com/HDRGainMap/1.0/";
+ const string Apdi = "http://ns.apple.com/pixeldatainfo/1.0/";
+ const string Container = "http://ns.google.com/photos/1.0/container/";
+ const string Item = "http://ns.google.com/photos/1.0/container/item/";
+ const string Camera = "http://ns.google.com/photos/1.0/camera/";
+ const string AppleGainMapType = "urn:com:apple:photo:2020:aux:hdrgainmap";
+
+ enum Shape { Version, Boolean, Real, RealOrThree, Integer, Long, AppleType }
+
+ // The order is the order they are written in.
+ static readonly (string Ns, string Name, string Prefix, Shape Shape)[] Properties = [
+ (Hdrgm, "Version", "hdrgm", Shape.Version),
+ (Hdrgm, "BaseRenditionIsHDR", "hdrgm", Shape.Boolean),
+ (Hdrgm, "GainMapMin", "hdrgm", Shape.RealOrThree),
+ (Hdrgm, "GainMapMax", "hdrgm", Shape.RealOrThree),
+ (Hdrgm, "Gamma", "hdrgm", Shape.RealOrThree),
+ (Hdrgm, "OffsetSDR", "hdrgm", Shape.RealOrThree),
+ (Hdrgm, "OffsetHDR", "hdrgm", Shape.RealOrThree),
+ (Hdrgm, "HDRCapacityMin", "hdrgm", Shape.Real),
+ (Hdrgm, "HDRCapacityMax", "hdrgm", Shape.Real),
+ (Apdi, "AuxiliaryImageType", "apdi", Shape.AppleType),
+ (Apdi, "NativeFormat", "apdi", Shape.Integer),
+ (Apdi, "StoredFormat", "apdi", Shape.Integer),
+ (AppleGainMap, "HDRGainMapVersion", "HDRGainMap", Shape.Integer),
+ (AppleGainMap, "HDRGainMapHeadroom", "HDRGainMap", Shape.Real),
+ (Camera, "MotionPhoto", "Camera", Shape.Integer),
+ (Camera, "MotionPhotoVersion", "Camera", Shape.Integer),
+ (Camera, "MotionPhotoPresentationTimestampUs", "Camera", Shape.Long),
+ ];
+
+ // Ultra HDR v1.0 and Motion Photo 1.0 (https://developer.android.com/media/platform/motion-photo-format)
+ // enumerate these; any other value is dropped (the item keeps its slot, its length and its padding).
+ static readonly string[] Semantics = ["Primary", "GainMap", "MotionPhoto"];
+ static readonly string[] MimeTypes = ["image/jpeg", "image/heic", "image/avif", "video/mp4", "video/quicktime"];
+
+ static readonly string[] ItemFields = ["Semantic", "Mime", "Length", "Padding"];
+
+ // Marks an rdf:li whose Container:Item was read; not one of ItemFields, so it is never written.
+ const string ItemSeen = "\0item";
+
+ /// Steps of the last read on this thread, for tests that bound it by an operation count.
+ [ThreadStatic]
+ internal static long Steps;
+
+ ///
+ /// The packet Clear keeps: null when it holds no valid gain-map property, otherwise a new packet that holds
+ /// only those properties.
+ ///
+ /// The packet bytes (UTF-8), possibly followed by NULs or padding.
+ /// The new lengths of the images after the first, in file order, or null.
+ /// True when the kept packet has HDRGainMapVersion and no
+ /// HDRGainMapHeadroom: decoders then take the headroom from the primary image's Apple maker note.
+ internal static byte[]? KeepForClear (ReadOnlySpan packet, IReadOnlyList? itemLengths, out bool headroomInMakerNote)
+ {
+ headroomInMakerNote = false;
+ var text = Encoding.UTF8.GetString (packet.ToArray ());
+ var end = text.LastIndexOf ('>');
+ if (end < 0)
+ return null;
+ var start = text.Length > 0 && text[0] == '' ? 1 : 0;
+ var found = new Found ();
+ try {
+ Read (text.Substring (start, end + 1 - start), found);
+ } catch (XmlException) {
+ return null;
+ }
+
+ if (found.Values.Count == 0 && found.Items is null)
+ return null;
+ if (found.Items is not null && itemLengths is not null)
+ SetItemLengths (found.Items, itemLengths);
+ headroomInMakerNote = found.Values.ContainsKey (Key ("HDRGainMap", "HDRGainMapVersion")) && !found.Values.ContainsKey (Key ("HDRGainMap", "HDRGainMapHeadroom"));
+ return Encoding.UTF8.GetBytes (Write (found));
+ }
+
+ sealed class Found
+ {
+ public Dictionary> Values { get; } = [];
+ public List>? Items { get; set; }
+ }
+
+ enum Role { Other, Rdf, Description, Property, PropertySeq, PropertyLi, Directory, DirectorySeq, DirectoryLi, DirectoryLiDescription, ItemNode, ItemDescription, ItemField }
+
+ sealed class Frame (Role role, string key)
+ {
+ public Role Role { get; } = role;
+ public string Key { get; } = key;
+ public StringBuilder? Text { get; set; }
+ public List? Values { get; set; }
+ public bool Invalid { get; set; }
+ }
+
+ static void Read (string packet, Found found)
+ {
+ var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreComments = true, IgnoreProcessingInstructions = true };
+ using var reader = XmlReader.Create (new StringReader (packet), settings);
+ var state = new ReadState ();
+ while (reader.Read ()) {
+ Steps++;
+ switch (reader.NodeType) {
+ case XmlNodeType.Element:
+ Open (reader, state, found);
+ break;
+ case XmlNodeType.Text:
+ case XmlNodeType.CDATA:
+ case XmlNodeType.SignificantWhitespace:
+ case XmlNodeType.Whitespace:
+ AppendText (reader, state.Stack);
+ break;
+ case XmlNodeType.EndElement: {
+ var frame = state.Stack[^1];
+ state.Stack.RemoveAt (state.Stack.Count - 1);
+ Close (frame, state.Stack, found, state.Item, ref state.Items, ref state.DirectoryDone);
+ break;
+ }
+ }
+ }
+ }
+
+ // The open elements, the directory's items so far and the one being read, and whether the directory is done.
+ sealed class ReadState
+ {
+ public readonly List Stack = [];
+ public List>? Items;
+ public Dictionary? Item;
+ public bool DirectoryDone;
+ }
+
+ static void Open (XmlReader reader, ReadState state, Found found)
+ {
+ var stack = state.Stack;
+ var parent = stack.Count > 0 ? stack[^1] : null;
+ var frame = Classify (reader, parent, found, state.DirectoryDone);
+ if (frame.Role == Role.Description)
+ ReadAttributes (reader, found.Values);
+ if (frame.Role == Role.Directory)
+ state.Items = [];
+ if (frame.Role == Role.DirectoryLi && state.Items is not null) {
+ state.Item = [];
+ state.Items.Add (state.Item);
+ }
+
+ if (frame.Role is Role.ItemNode or Role.ItemDescription && state.Item is not null) {
+ state.Item[ItemSeen] = "";
+ ReadItemAttributes (reader, state.Item);
+ }
+
+ // Anything but the expected shape inside a kept value makes that value invalid: it is dropped.
+ if (frame.Role == Role.Other && parent is not null) {
+ if (parent.Role == Role.ItemField)
+ parent.Invalid = true;
+ else
+ InvalidateProperty (stack);
+ }
+
+ if (reader.IsEmptyElement)
+ Close (frame, stack, found, state.Item, ref state.Items, ref state.DirectoryDone);
+ else
+ stack.Add (frame);
+ }
+
+ static void AppendText (XmlReader reader, List stack)
+ {
+ if (stack.Count == 0 || stack[^1].Role is not (Role.Property or Role.PropertyLi or Role.ItemField))
+ return;
+ var top = stack[^1];
+ top.Text ??= new StringBuilder ();
+ if (top.Text.Length <= 64)
+ top.Text.Append (reader.Value);
+ }
+
+ static Frame Classify (XmlReader reader, Frame? parent, Found found, bool directoryDone)
+ {
+ var ns = reader.NamespaceURI;
+ var name = reader.LocalName;
+ var role = parent?.Role;
+ if (ns == Rdf && name == "RDF")
+ return new Frame (Role.Rdf, "");
+ if (role == Role.Rdf)
+ return new Frame (ns == Rdf && name == "Description" ? Role.Description : Role.Other, "");
+ if (role == Role.Description) {
+ if (ns == Container && name == "Directory" && !directoryDone)
+ return new Frame (Role.Directory, "");
+ foreach (var property in Properties) {
+ if (property.Ns == ns && property.Name == name && !found.Values.ContainsKey (Key (property.Prefix, name)))
+ return new Frame (Role.Property, Key (property.Prefix, name)) { Values = [] };
+ }
+
+ return new Frame (Role.Other, "");
+ }
+
+ if (role == Role.Property && ns == Rdf && name is "Seq" or "Bag" or "Alt")
+ return new Frame (Role.PropertySeq, parent!.Key);
+ if (role == Role.PropertySeq && ns == Rdf && name == "li")
+ return new Frame (Role.PropertyLi, parent!.Key);
+ if (role == Role.Directory && ns == Rdf && name == "Seq")
+ return new Frame (Role.DirectorySeq, "");
+ if (role == Role.DirectorySeq && ns == Rdf && name == "li")
+ return new Frame (Role.DirectoryLi, "");
+ // An item is rdf:li > Container:Item, or the RDF struct form rdf:li > rdf:Description > Container:Item.
+ if (role == Role.DirectoryLi && ns == Rdf && name == "Description")
+ return new Frame (Role.DirectoryLiDescription, "");
+ if (role is Role.DirectoryLi or Role.DirectoryLiDescription && ns == Container && name == "Item")
+ return new Frame (Role.ItemNode, "");
+ if (role == Role.ItemNode && ns == Rdf && name == "Description")
+ return new Frame (Role.ItemDescription, "");
+ if (role is Role.ItemNode or Role.ItemDescription && ns == Item && Array.IndexOf (ItemFields, name) >= 0)
+ return new Frame (Role.ItemField, name);
+ return new Frame (Role.Other, "");
+ }
+
+ // The property a frame on top of the stack belongs to (Property, or Property > Seq > li), or null.
+ static Frame? EnclosingProperty (List stack)
+ {
+ for (var n = stack.Count - 1; n >= 0 && n >= stack.Count - 3; n--) {
+ if (stack[n].Role == Role.Property)
+ return stack[n];
+ if (stack[n].Role is not (Role.PropertySeq or Role.PropertyLi))
+ return null;
+ }
+
+ return null;
+ }
+
+ static void InvalidateProperty (List stack)
+ {
+ if (EnclosingProperty (stack) is Frame property)
+ property.Invalid = true;
+ }
+
+ static void Close (Frame frame, List stack, Found found, Dictionary? item, ref List>? items, ref bool directoryDone)
+ {
+ switch (frame.Role) {
+ case Role.Property: {
+ if (frame.Invalid || found.Values.ContainsKey (frame.Key))
+ return;
+ var values = frame.Values!.Count > 0 ? frame.Values : frame.Text is null ? [] : [frame.Text.ToString ().Trim ()];
+ if (IsValid (frame.Key, values))
+ found.Values[frame.Key] = values;
+ return;
+ }
+
+ case Role.PropertyLi: {
+ var property = EnclosingProperty (stack);
+ if (property is null)
+ return;
+ if (frame.Invalid || frame.Text is null)
+ property.Invalid = true;
+ else
+ property.Values!.Add (frame.Text.ToString ().Trim ());
+ return;
+ }
+
+ case Role.ItemField:
+ if (!frame.Invalid && item is not null && frame.Text is not null && !item.ContainsKey (frame.Key) && IsItemValue (frame.Key, frame.Text.ToString ().Trim ()))
+ item[frame.Key] = frame.Text.ToString ().Trim ();
+ return;
+
+ case Role.Directory:
+ // Readers locate items by their order and lengths, so a slot is never removed: when one rdf:li
+ // holds no Container:Item that can be read, the whole directory is dropped.
+ if (items is { Count: > 0 } && found.Items is null && items.TrueForAll (i => i.ContainsKey (ItemSeen)))
+ found.Items = items;
+ directoryDone = true;
+ items = null;
+ return;
+ }
+ }
+
+ static void ReadAttributes (XmlReader reader, Dictionary> values)
+ {
+ if (!reader.MoveToFirstAttribute ())
+ return;
+ do {
+ foreach (var property in Properties) {
+ if (property.Ns != reader.NamespaceURI || property.Name != reader.LocalName)
+ continue;
+ var key = Key (property.Prefix, property.Name);
+ if (!values.ContainsKey (key) && IsValid (key, [reader.Value.Trim ()]))
+ values[key] = [reader.Value.Trim ()];
+ }
+ } while (reader.MoveToNextAttribute ());
+ reader.MoveToElement ();
+ }
+
+ static void ReadItemAttributes (XmlReader reader, Dictionary item)
+ {
+ if (!reader.MoveToFirstAttribute ())
+ return;
+ do {
+ if (reader.NamespaceURI == Item && Array.IndexOf (ItemFields, reader.LocalName) >= 0 && !item.ContainsKey (reader.LocalName) && IsItemValue (reader.LocalName, reader.Value.Trim ()))
+ item[reader.LocalName] = reader.Value.Trim ();
+ } while (reader.MoveToNextAttribute ());
+ reader.MoveToElement ();
+ }
+
+ static string Key (string prefix, string name) => prefix + ":" + name;
+
+ static Shape ShapeOf (string key)
+ {
+ foreach (var property in Properties) {
+ if (Key (property.Prefix, property.Name) == key)
+ return property.Shape;
+ }
+
+ return Shape.Real;
+ }
+
+ static bool IsValid (string key, List values)
+ {
+ var shape = ShapeOf (key);
+ if (shape == Shape.RealOrThree)
+ return values.Count == 1 ? IsReal (values[0]) : values.Count == 3 && values.TrueForAll (IsReal);
+ if (values.Count != 1)
+ return false;
+ var value = values[0];
+ return shape switch {
+ Shape.Version => IsVersion (value),
+ Shape.Boolean => value is "True" or "False",
+ Shape.Real => IsReal (value),
+ Shape.Integer => IsInteger (value),
+ Shape.Long => IsInteger (value) || (value.Length > 1 && value[0] == '-' && IsInteger (value.Substring (1))),
+ Shape.AppleType => value == AppleGainMapType,
+ _ => false
+ };
+ }
+
+ static bool IsItemValue (string field, string value) => field switch {
+ "Semantic" => Array.IndexOf (Semantics, value) >= 0,
+ "Mime" => Array.IndexOf (MimeTypes, value) >= 0,
+ _ => IsInteger (value)
+ };
+
+ // "1.0": digits, one dot, digits.
+ static bool IsVersion (string value)
+ {
+ if (value.Length is 0 or > 16)
+ return false;
+ var dots = 0;
+ for (var i = 0; i < value.Length; i++) {
+ if (value[i] == '.') {
+ if (i == 0 || i == value.Length - 1 || ++dots > 1)
+ return false;
+ } else if (value[i] is < '0' or > '9') {
+ return false;
+ }
+ }
+
+ return dots == 1;
+ }
+
+ static bool IsReal (string value) =>
+ value.Length is > 0 and <= 32
+ && double.TryParse (value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
+ && !double.IsNaN (number) && !double.IsInfinity (number);
+
+ static bool IsInteger (string value) =>
+ value.Length is > 0 and <= 19 && value.All (c => c is >= '0' and <= '9');
+
+ // The first item is the primary; the next lengths.Count items are the later MPF images in file order. Items
+ // after those (a motion-photo video, which Clear copies as it is) keep their lengths.
+ static void SetItemLengths (List> items, IReadOnlyList lengths)
+ {
+ for (var n = 1; n < items.Count && n - 1 < lengths.Count; n++)
+ items[n]["Length"] = lengths[n - 1].ToString (CultureInfo.InvariantCulture);
+ }
+
+ static string Write (Found found)
+ {
+ var builder = new StringBuilder (512);
+ builder.Append ("");
+ builder.Append ("");
+ builder.Append ("');
+ WriteElements (builder, found);
+ if (found.Items is not null)
+ WriteDirectory (builder, found.Items);
+ builder.Append ("");
+ return builder.ToString ();
+ }
+
+ static void WriteNamespaces (StringBuilder builder, Found found)
+ {
+ var used = new HashSet ();
+ foreach (var property in Properties) {
+ if (found.Values.ContainsKey (Key (property.Prefix, property.Name)) && used.Add (property.Prefix))
+ builder.Append (" xmlns:").Append (property.Prefix).Append ("=\"").Append (property.Ns).Append ('"');
+ }
+
+ if (found.Items is not null)
+ builder.Append (" xmlns:Container=\"").Append (Container).Append ("\" xmlns:Item=\"").Append (Item).Append ('"');
+ }
+
+ // Ultra HDR writes single values as attributes (the format's examples); arrays and Apple's properties
+ // (as ImageIO writes them) are elements.
+ static bool IsAttribute (string ns, List values) => ns is Hdrgm or Camera && values.Count == 1;
+
+ static void WriteAttributes (StringBuilder builder, Found found)
+ {
+ foreach (var property in Properties) {
+ var key = Key (property.Prefix, property.Name);
+ if (found.Values.TryGetValue (key, out var values) && IsAttribute (property.Ns, values))
+ builder.Append (' ').Append (key).Append ("=\"").Append (Escape (values[0])).Append ('"');
+ }
+ }
+
+ static void WriteElements (StringBuilder builder, Found found)
+ {
+ foreach (var property in Properties) {
+ var key = Key (property.Prefix, property.Name);
+ if (!found.Values.TryGetValue (key, out var values) || IsAttribute (property.Ns, values))
+ continue;
+ builder.Append ('<').Append (key).Append ('>');
+ if (values.Count == 1) {
+ builder.Append (Escape (values[0]));
+ } else {
+ builder.Append ("");
+ foreach (var value in values)
+ builder.Append ("").Append (Escape (value)).Append ("");
+ builder.Append ("");
+ }
+
+ builder.Append ("").Append (key).Append ('>');
+ }
+ }
+
+ static void WriteDirectory (StringBuilder builder, List> items)
+ {
+ builder.Append ("");
+ foreach (var item in items) {
+ builder.Append ("");
+ }
+
+ builder.Append ("");
+ }
+
+ static string Escape (string value)
+ {
+ var builder = new StringBuilder (value.Length);
+ foreach (var c in value) {
+ if (c == '&')
+ builder.Append ("&");
+ else if (c == '<')
+ builder.Append ("<");
+ else if (c == '"')
+ builder.Append (""");
+ else
+ builder.Append (c);
+ }
+
+ return builder.ToString ();
+ }
+}
diff --git a/src/TagLibSharp2/Image/ImageHeader.cs b/src/TagLibSharp2/Image/ImageHeader.cs
new file mode 100644
index 00000000..d6261626
--- /dev/null
+++ b/src/TagLibSharp2/Image/ImageHeader.cs
@@ -0,0 +1,219 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Core;
+using TagLibSharp2.Image.Jpeg;
+using TagLibSharp2.Image.Svg;
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image;
+
+///
+/// Detects the still-image formats and reads their dimensions from the container, not from Exif. PNG IHDR is the
+/// PNG specification, GIF the logical screen of GIF89a, BMP the DIB header, PCX the ZSoft window and Netpbm the
+/// P1-P6 raster header; JPEG, TIFF and DNG, and SVG have their own readers (,
+/// , ).
+///
+internal static class ImageHeader
+{
+ public static bool TryDetect (ReadOnlySpan data, out MediaFormat format)
+ {
+ format = JpegSize.IsJpeg (data) ? MediaFormat.Jpeg
+ : IsPng (data) ? MediaFormat.Png
+ : IsGif (data) ? MediaFormat.Gif
+ : IsBmp (data) ? MediaFormat.Bmp
+ : IsPcx (data) ? MediaFormat.Pcx
+ : IsNetpbm (data) ? MediaFormat.Netpbm
+ : TiffReader.IsTiff (data) ? TiffSize.HasDngVersion (data) ? MediaFormat.Dng : MediaFormat.Tiff
+ : SvgSize.IsSvg (data) ? MediaFormat.Svg
+ : MediaFormat.Unknown;
+ return format != MediaFormat.Unknown;
+ }
+
+ public static bool TryRead (ReadOnlySpan data, MediaFormat format, out ImageProperties? properties)
+ {
+ properties = null;
+ return format switch {
+ MediaFormat.Jpeg => JpegSize.TryRead (data, out properties),
+ MediaFormat.Png => TryPng (data, out properties),
+ MediaFormat.Gif => TryGif (data, out properties),
+ MediaFormat.Bmp => TryBmp (data, out properties),
+ MediaFormat.Pcx => TryPcx (data, out properties),
+ MediaFormat.Netpbm => TryNetpbm (data, out properties),
+ MediaFormat.Tiff => TiffSize.TryRead (data, dng: false, out properties),
+ MediaFormat.Dng => TiffSize.TryRead (data, dng: true, out properties),
+ MediaFormat.Svg => SvgSize.TryRead (data, out properties),
+ _ => false
+ };
+ }
+
+ // 0x89 must be written as a byte. In a UTF-8 literal, \x89 is U+0089 and encodes as C2 89.
+ static bool IsPng (ReadOnlySpan data) =>
+ data.Length >= 8
+ && data[0] == 0x89 && data[1] == (byte)'P' && data[2] == (byte)'N' && data[3] == (byte)'G'
+ && data[4] == 0x0D && data[5] == 0x0A && data[6] == 0x1A && data[7] == 0x0A;
+
+ static bool TryPng (ReadOnlySpan data, out ImageProperties? properties)
+ {
+ properties = null;
+ if (!IsPng (data) || data.Length < 29 || !data.Slice (12, 4).SequenceEqual ("IHDR"u8))
+ return false;
+
+ var width = Endian.I32 (data, 16, le: false);
+ var height = Endian.I32 (data, 20, le: false);
+ if (width <= 0 || height <= 0)
+ return false;
+
+ var bitDepth = data[24];
+ var samples = data[25] switch {
+ 0 => 1,
+ 2 => 3,
+ 3 => 1,
+ 4 => 2,
+ 6 => 4,
+ _ => 0
+ };
+ if (samples == 0)
+ return false;
+
+ properties = new ImageProperties (width, height, bitDepth * samples, "PNG");
+ return true;
+ }
+
+ static bool IsGif (ReadOnlySpan data) =>
+ data.Length >= 6 && (data.StartsWith ("GIF87a"u8) || data.StartsWith ("GIF89a"u8));
+
+ static bool TryGif (ReadOnlySpan data, out ImageProperties? properties)
+ {
+ properties = null;
+ if (!IsGif (data) || data.Length < 13)
+ return false;
+
+ var width = Endian.U16 (data, 6, le: true);
+ var height = Endian.U16 (data, 8, le: true);
+ if (width <= 0 || height <= 0)
+ return false;
+
+ var depth = (data[10] & 0x07) + 1;
+ properties = new ImageProperties (width, height, depth, "GIF");
+ return true;
+ }
+
+ static bool IsBmp (ReadOnlySpan data) =>
+ data.Length >= 26 && data[0] == (byte)'B' && data[1] == (byte)'M';
+
+ static bool TryBmp (ReadOnlySpan data, out ImageProperties? properties)
+ {
+ properties = null;
+ if (!IsBmp (data))
+ return false;
+
+ var header = Endian.I32 (data, 14, le: true);
+ int width;
+ int height;
+ var depth = 0;
+ if (header == 12) {
+ if (data.Length < 26)
+ return false;
+ width = Endian.U16 (data, 18, le: true);
+ height = Endian.U16 (data, 20, le: true);
+ depth = Endian.U16 (data, 24, le: true);
+ } else if (header >= 16 && data.Length >= 26) {
+ width = Endian.I32 (data, 18, le: true);
+ var rawHeight = Endian.I32 (data, 22, le: true);
+ if (rawHeight == int.MinValue)
+ return false;
+ height = rawHeight < 0 ? -rawHeight : rawHeight;
+ if (data.Length >= 30)
+ depth = Endian.U16 (data, 28, le: true);
+ } else {
+ return false;
+ }
+
+ if (width <= 0 || height <= 0)
+ return false;
+
+ properties = new ImageProperties (width, height, depth, "BMP");
+ return true;
+ }
+
+ static bool IsPcx (ReadOnlySpan data) =>
+ data.Length >= 12 && data[0] == 0x0A && data[1] <= 5 && data[2] <= 1;
+
+ static bool TryPcx (ReadOnlySpan data, out ImageProperties? properties)
+ {
+ properties = null;
+ if (!IsPcx (data))
+ return false;
+
+ var xmin = Endian.U16 (data, 4, le: true);
+ var ymin = Endian.U16 (data, 6, le: true);
+ var xmax = Endian.U16 (data, 8, le: true);
+ var ymax = Endian.U16 (data, 10, le: true);
+ if (xmax < xmin || ymax < ymin)
+ return false;
+
+ var depth = (int)data[3];
+ if (data.Length >= 66 && data[65] > 0)
+ depth *= data[65];
+
+ properties = new ImageProperties (xmax - xmin + 1, ymax - ymin + 1, depth, "PCX");
+ return true;
+ }
+
+ static bool IsNetpbm (ReadOnlySpan data) =>
+ data.Length >= 3 && data[0] == (byte)'P' && data[1] is >= (byte)'1' and <= (byte)'6' && IsSpace (data[2]);
+
+ static bool TryNetpbm (ReadOnlySpan data, out ImageProperties? properties)
+ {
+ properties = null;
+ if (!IsNetpbm (data))
+ return false;
+
+ var i = 2;
+ if (!TryNetpbmInt (data, ref i, out var width) || !TryNetpbmInt (data, ref i, out var height))
+ return false;
+ if (width <= 0 || height <= 0)
+ return false;
+
+ var kind = data[1] switch {
+ (byte)'1' or (byte)'4' => "PBM",
+ (byte)'2' or (byte)'5' => "PGM",
+ _ => "PPM"
+ };
+ properties = new ImageProperties (width, height, 0, kind);
+ return true;
+ }
+
+ static bool TryNetpbmInt (ReadOnlySpan data, ref int i, out int value)
+ {
+ value = 0;
+ while (i < data.Length) {
+ if (data[i] == (byte)'#') {
+ while (i < data.Length && data[i] != (byte)'\n')
+ i++;
+ } else if (IsSpace (data[i])) {
+ i++;
+ } else {
+ break;
+ }
+ }
+
+ if (i >= data.Length || data[i] is < (byte)'0' or > (byte)'9')
+ return false;
+
+ var acc = 0;
+ while (i < data.Length && data[i] is >= (byte)'0' and <= (byte)'9') {
+ var digit = data[i] - (byte)'0';
+ if (acc > (1_000_000_000 - digit) / 10)
+ return false;
+ acc = (acc * 10) + digit;
+ i++;
+ }
+
+ value = acc;
+ return true;
+ }
+
+ static bool IsSpace (byte value) => value is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n';
+}
diff --git a/src/TagLibSharp2/Image/ImagePlan.cs b/src/TagLibSharp2/Image/ImagePlan.cs
new file mode 100644
index 00000000..34ea6dfc
--- /dev/null
+++ b/src/TagLibSharp2/Image/ImagePlan.cs
@@ -0,0 +1,340 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Core;
+
+namespace TagLibSharp2.Image;
+
+///
+/// Ordered new bytes and ranges of the original file. Rendering and writing are separate.
+///
+sealed class ImagePlan
+{
+ readonly List _pieces = [];
+
+ /// Gets the number of bytes the plan produces.
+ public long Length { get; private set; }
+
+ /// Gets the exclusive end of the furthest original-file range.
+ public long SourceEnd {
+ get {
+ long end = 0;
+ foreach (var piece in _pieces) {
+ if (!piece.IsRange)
+ continue;
+ var pieceEnd = piece.Offset + piece.Length;
+ if (pieceEnd > end)
+ end = pieceEnd;
+ }
+
+ return end;
+ }
+ }
+
+ /// One range covering the whole original file.
+ /// Length of the original file.
+ public static ImagePlan Whole (int length)
+ {
+ var plan = new ImagePlan ();
+ plan.Copy (0, length);
+ return plan;
+ }
+
+ /// Appends bytes that are not in the original file.
+ /// The new bytes. Empty appends nothing.
+ public void Add (ReadOnlySpan bytes)
+ {
+ if (bytes.IsEmpty)
+ return;
+
+ Add (bytes.ToArray ());
+ }
+
+ /// Appends bytes that are not in the original file.
+ /// The new bytes. Empty appends nothing. The array is kept.
+ public void Add (byte[] bytes)
+ {
+ if (bytes.Length == 0)
+ return;
+
+ AddLiteral (_pieces, bytes);
+ Length += bytes.Length;
+ }
+
+ /// Appends a range of the original file. Adjacent ranges become one.
+ /// Offset in the original file.
+ /// Number of bytes. Zero appends nothing.
+ public void Copy (long offset, long count)
+ {
+ if (count == 0)
+ return;
+
+#if NETSTANDARD2_0 || NETSTANDARD2_1
+ if (count < 0)
+ throw new ArgumentOutOfRangeException (nameof (count));
+#else
+ ArgumentOutOfRangeException.ThrowIfNegative (count);
+#endif
+ AddRange (_pieces, offset, count);
+ Length += count;
+ }
+
+ /// Appends another plan. Its ranges keep their original-file offsets.
+ /// Plan to append.
+ public void Append (ImagePlan other)
+ {
+ foreach (var piece in other._pieces) {
+ if (piece.IsRange)
+ Copy (piece.Offset, piece.Length);
+ else
+ Add (piece.Bytes!);
+ }
+ }
+
+ /// Copies the plan into one buffer.
+ /// The original file.
+ /// The bytes the plan produces.
+ public byte[] Materialize (ReadOnlySpan source)
+ {
+ var output = new byte[checked((int)Length)];
+ var dest = 0;
+ foreach (var piece in _pieces) {
+ var count = checked((int)piece.Length);
+ CopyPiece (piece, 0, count, source, output.AsSpan (dest, count));
+ dest += count;
+ }
+
+ return output;
+ }
+
+ ///
+ /// Returns when the plan is that whole file; otherwise .
+ ///
+ /// The original file.
+ public ReadOnlyMemory MaterializeShared (byte[] source)
+ {
+ if (_pieces.Count == 1 && _pieces[0].IsRange && _pieces[0].Offset == 0 && _pieces[0].Length == source.Length)
+ return source;
+
+ return Materialize (source);
+ }
+
+ /// Copies one span of the output.
+ /// Offset in the output.
+ /// Number of bytes.
+ /// The original file, for ranges.
+ public byte[] MaterializeRange (long start, long count, ReadOnlySpan source)
+ {
+ if (start < 0 || count < 0 || start > Length || count > Length - start)
+ throw new ArgumentOutOfRangeException (nameof (start));
+
+ var output = new byte[checked((int)count)];
+ if (count == 0)
+ return output;
+
+ var filled = 0;
+ var skip = start;
+ foreach (var piece in _pieces) {
+ if (skip >= piece.Length) {
+ skip -= piece.Length;
+ continue;
+ }
+
+ var take = (int)Math.Min (piece.Length - skip, count - filled);
+ CopyPiece (piece, skip, take, source, output.AsSpan (filled, take));
+ filled += take;
+ skip = 0;
+ if (filled == count)
+ return output;
+ }
+
+ throw new ArgumentOutOfRangeException (nameof (count));
+ }
+
+ /// Removes an output span. Ranges on either side keep their original-file offsets.
+ /// Offset in the output.
+ /// Number of bytes removed. Zero removes nothing.
+ public void Cut (long start, long count)
+ {
+ if (count == 0)
+ return;
+
+ if (start < 0 || count < 0 || start > Length || count > Length - start)
+ throw new ArgumentOutOfRangeException (nameof (start));
+
+ ReplaceSpan (start, start + count, null);
+ Length -= count;
+ }
+
+ /// Replaces an output span with of the same length.
+ /// Offset in the output.
+ /// Number of bytes replaced.
+ /// The new bytes. Its length is .
+ public void Splice (long start, long count, byte[] replacement)
+ {
+ if (count == 0)
+ return;
+
+ if (start < 0 || count < 0 || start > Length || count > Length - start || replacement.Length != count)
+ throw new ArgumentOutOfRangeException (nameof (start));
+
+ ReplaceSpan (start, start + count, replacement);
+ }
+
+ // insert null removes the span. Otherwise the span is replaced by those bytes.
+ void ReplaceSpan (long start, long end, byte[]? insert)
+ {
+ var next = new List (_pieces.Count + 1);
+ long at = 0;
+ var inserted = insert is null;
+ foreach (var piece in _pieces) {
+ var pieceEnd = at + piece.Length;
+ if (pieceEnd <= start || at >= end) {
+ AddExisting (next, piece);
+ } else {
+ var before = start > at ? start - at : 0;
+ if (before > 0)
+ AddSlice (next, piece, 0, before);
+ if (!inserted) {
+ AddLiteral (next, insert!);
+ inserted = true;
+ }
+
+ var after = pieceEnd > end ? pieceEnd - end : 0;
+ if (after > 0)
+ AddSlice (next, piece, piece.Length - after, after);
+ }
+
+ at = pieceEnd;
+ }
+
+ if (!inserted)
+ throw new ArgumentOutOfRangeException (nameof (start));
+
+ _pieces.Clear ();
+ _pieces.AddRange (next);
+ }
+
+ ///
+ /// Writes the plan. Ranges come from when it is set, and from
+ /// when it is not. New bytes are written as they are.
+ ///
+ /// Original file, or null to read ranges from .
+ /// Original bytes used when is null.
+ /// Stream that receives the output.
+ /// Buffer from .
+ /// Checked before each chunk. Cancelled copies throw.
+ public void Write (
+ Stream? source,
+ ReadOnlySpan held,
+ Stream destination,
+ byte[] chunk,
+ CancellationToken cancellationToken = default)
+ {
+ foreach (var piece in _pieces) {
+ if (!piece.IsRange) {
+ WriteChunked (destination, piece.Bytes, chunk, cancellationToken);
+ continue;
+ }
+
+ if (source is not null) {
+ if (source.Position != piece.Offset)
+ source.Position = piece.Offset;
+ CopyChunked (source, destination, piece.Length, chunk, cancellationToken);
+ continue;
+ }
+
+ var offset = checked((int)piece.Offset);
+ var count = checked((int)piece.Length);
+ WriteChunked (destination, held.Slice (offset, count), chunk, cancellationToken);
+ }
+ }
+
+ // One StreamCopy call is at most one chunk, so a cancel during a write stops the next chunk.
+ static void CopyChunked (
+ Stream source,
+ Stream destination,
+ long count,
+ byte[] chunk,
+ CancellationToken cancellationToken)
+ {
+ var left = count;
+ while (left > 0) {
+ cancellationToken.ThrowIfCancellationRequested ();
+ var take = left < StreamCopy.ChunkSize ? left : StreamCopy.ChunkSize;
+ StreamCopy.Copy (source, destination, take, chunk);
+ left -= take;
+ }
+ }
+
+ static void WriteChunked (
+ Stream destination,
+ ReadOnlySpan data,
+ byte[] chunk,
+ CancellationToken cancellationToken)
+ {
+ var offset = 0;
+ while (offset < data.Length) {
+ cancellationToken.ThrowIfCancellationRequested ();
+ var count = Math.Min (StreamCopy.ChunkSize, data.Length - offset);
+ StreamCopy.Write (destination, data.Slice (offset, count), chunk);
+ offset += count;
+ }
+ }
+
+ static void CopyPiece (Piece piece, long skip, int take, ReadOnlySpan source, Span destination)
+ {
+ if (piece.IsRange)
+ source.Slice (checked((int)(piece.Offset + skip)), take).CopyTo (destination);
+ else
+ piece.Bytes!.AsSpan (checked((int)skip), take).CopyTo (destination);
+ }
+
+ static void AddExisting (List pieces, Piece piece)
+ {
+ if (piece.IsRange)
+ AddRange (pieces, piece.Offset, piece.Length);
+ else
+ AddLiteral (pieces, piece.Bytes!);
+ }
+
+ static void AddSlice (List pieces, Piece piece, long skip, long count)
+ {
+ if (count == 0)
+ return;
+
+ if (piece.IsRange) {
+ AddRange (pieces, piece.Offset + skip, count);
+ return;
+ }
+
+ var slice = new byte[checked((int)count)];
+ piece.Bytes!.AsSpan (checked((int)skip), slice.Length).CopyTo (slice);
+ AddLiteral (pieces, slice);
+ }
+
+ // Each new piece stays its own entry. Copying it onto the previous piece would copy every byte gathered so
+ // far, once per piece.
+ static void AddLiteral (List pieces, byte[] bytes)
+ {
+ if (bytes.Length == 0)
+ return;
+
+ pieces.Add (new Piece (false, 0, bytes.Length, bytes));
+ }
+
+ static void AddRange (List pieces, long offset, long count)
+ {
+ if (pieces.Count > 0) {
+ var last = pieces[^1];
+ if (last.IsRange && last.Offset + last.Length == offset) {
+ pieces[^1] = new Piece (true, last.Offset, last.Length + count, null);
+ return;
+ }
+ }
+
+ pieces.Add (new Piece (true, offset, count, null));
+ }
+
+ readonly record struct Piece (bool IsRange, long Offset, long Length, byte[]? Bytes);
+}
diff --git a/src/TagLibSharp2/Image/ImageRewrite.cs b/src/TagLibSharp2/Image/ImageRewrite.cs
new file mode 100644
index 00000000..8eac3d1b
--- /dev/null
+++ b/src/TagLibSharp2/Image/ImageRewrite.cs
@@ -0,0 +1,108 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Diagnostics.CodeAnalysis;
+using TagLibSharp2.Core;
+using TagLibSharp2.Image.Gif;
+using TagLibSharp2.Image.Jpeg;
+using TagLibSharp2.Image.Png;
+
+namespace TagLibSharp2.Image;
+
+///
+/// Reads and splices the text blocks an image format already defines: PNG tEXt, zTXt and iTXt, the GIF comment
+/// extension, and the JPEG COM marker before the scan. Pixel bytes are copied through.
+///
+static class ImageRewrite
+{
+ internal static ImageTag? CreateTag (ReadOnlySpan data, MediaFormat format)
+ {
+ var stores = format switch {
+ MediaFormat.Png => ImageStores.Png,
+ MediaFormat.Gif or MediaFormat.Jpeg => ImageStores.CommentOnly,
+ _ => ImageStores.None
+ };
+ if (stores == ImageStores.None)
+ return null;
+
+ var tag = new ImageTag (format, stores);
+ if (format == MediaFormat.Png)
+ PngRewriter.Read (data, tag);
+ else if (format == MediaFormat.Gif)
+ GifRewriter.Read (data, tag);
+ else
+ JpegRewriter.Read (data, tag);
+ return tag;
+ }
+
+ internal static byte[] RenderTag (ImageTag tag)
+ {
+ using var builder = new BinaryDataBuilder ();
+ if (tag.Format == MediaFormat.Png)
+ PngRewriter.AddFields (builder, tag, onlyChanged: false);
+ else if (tag.Field (ImageStores.Comment) is string comment) {
+ if (tag.Format == MediaFormat.Gif)
+ GifRewriter.AddComment (builder, comment);
+ else
+ builder.Add (JpegRewriter.EncodeComment (comment));
+ }
+
+ return builder.ToArray ();
+ }
+
+ /// A plan for a format whose path save copies original ranges. False when the container cannot be updated.
+ internal static bool TryPlan (
+ ReadOnlySpan data,
+ MediaFormat format,
+ ImageTag? tag,
+ [NotNullWhen (true)] out ImagePlan? plan,
+ [NotNullWhen (false)] out string? error)
+ {
+ error = null;
+ if (format == MediaFormat.Png)
+ return TryEditedPlan (data, tag, PngRewriter.Plan, PngRewriter.SpliceError, out plan, out error);
+ if (format == MediaFormat.Gif)
+ return TryEditedPlan (data, tag, GifRewriter.Plan, GifRewriter.SpliceError, out plan, out error);
+ if (format == MediaFormat.Jpeg)
+ return TryEditedPlan (data, tag, JpegRewriter.Plan, JpegRewriter.SpliceError, out plan, out error);
+ if (CopiesWholeFile (format)) {
+ plan = ImagePlan.Whole (data.Length);
+ return true;
+ }
+
+ plan = null;
+ error = "The image container could not be updated.";
+ return false;
+ }
+
+ ///
+ /// An unchanged file is one range of the original. An edit is that format's plan, or its splice error.
+ ///
+ static bool TryEditedPlan (
+ ReadOnlySpan data,
+ ImageTag? tag,
+ RewriterPlan build,
+ string spliceError,
+ [NotNullWhen (true)] out ImagePlan? plan,
+ [NotNullWhen (false)] out string? error)
+ {
+ error = null;
+ if (tag is null || !tag.AffectsFile) {
+ plan = ImagePlan.Whole (data.Length);
+ return true;
+ }
+
+ plan = build (data, tag, out error);
+ if (plan is null && error is null)
+ error = spliceError;
+ return plan is not null;
+ }
+
+ delegate ImagePlan? RewriterPlan (ReadOnlySpan data, ImageTag tag, out string? error);
+
+ /// These formats have no metadata rewriter, so the plan is the original file.
+ static bool CopiesWholeFile (MediaFormat format) =>
+ format is MediaFormat.Tiff or MediaFormat.Dng
+ or MediaFormat.Bmp or MediaFormat.Pcx
+ or MediaFormat.Netpbm or MediaFormat.Svg;
+}
diff --git a/src/TagLibSharp2/Image/ImageTag.cs b/src/TagLibSharp2/Image/ImageTag.cs
new file mode 100644
index 00000000..584fd36c
--- /dev/null
+++ b/src/TagLibSharp2/Image/ImageTag.cs
@@ -0,0 +1,191 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Core;
+
+namespace TagLibSharp2.Image;
+
+[Flags]
+enum ImageStores
+{
+ None = 0,
+ Title = 1 << 0,
+ Artist = 1 << 1,
+ Description = 1 << 2,
+ Copyright = 1 << 3,
+ Year = 1 << 4,
+ Comment = 1 << 5,
+ Png = Title | Artist | Description | Copyright | Year | Comment,
+ CommentOnly = Comment
+}
+
+///
+/// Text stored in an image file. PNG keeps the standard text keywords.
+/// GIF and JPEG keep the comment. A field the format does not store reads
+/// back as null, and assigning it changes nothing.
+///
+sealed class ImageTag : Tag
+{
+ readonly ImageStores _stores;
+ ImageStores _dirty;
+ string? _title;
+ string? _artist;
+ string? _description;
+ string? _copyright;
+ string? _year;
+ string? _comment;
+
+ internal ImageTag (MediaFormat format, ImageStores stores)
+ {
+ Format = format;
+ _stores = stores;
+ }
+
+ internal MediaFormat Format { get; }
+
+ /// Clear asked the rewriter to drop text it does not map onto a field.
+ internal bool DropUnmapped { get; private set; }
+
+ internal bool AffectsFile => _dirty != 0 || DropUnmapped;
+
+ internal bool Changed (ImageStores field) => (_dirty & field) != 0;
+
+ internal string? Field (ImageStores field) => field switch {
+ ImageStores.Title => _title,
+ ImageStores.Artist => _artist,
+ ImageStores.Description => _description,
+ ImageStores.Copyright => _copyright,
+ ImageStores.Year => _year,
+ ImageStores.Comment => _comment,
+ _ => null
+ };
+
+ internal void ReadField (ImageStores field, string? value)
+ {
+ if (field == ImageStores.None || (_stores & field) == 0)
+ return;
+ Assign (field, string.IsNullOrEmpty (value) ? null : value, markDirty: false);
+ }
+
+ ///
+ public override TagTypes TagType => TagTypes.Image;
+
+ ///
+ public override string? Title {
+ get => _title;
+ set => Assign (ImageStores.Title, value, markDirty: true);
+ }
+
+ ///
+ public override string? Artist {
+ get => _artist;
+ set => Assign (ImageStores.Artist, value, markDirty: true);
+ }
+
+ ///
+ public override string? Album {
+ get => null;
+ set { }
+ }
+
+ ///
+ public override string? Year {
+ get => _year;
+ set => Assign (ImageStores.Year, value, markDirty: true);
+ }
+
+ ///
+ public override string? Comment {
+ get => _comment;
+ set => Assign (ImageStores.Comment, value, markDirty: true);
+ }
+
+ ///
+ public override string? Genre {
+ get => null;
+ set { }
+ }
+
+ ///
+ public override uint? Track {
+ get => null;
+ set { }
+ }
+
+ ///
+ public override string? Description {
+ get => _description;
+ set => Assign (ImageStores.Description, value, markDirty: true);
+ }
+
+ ///
+ public override string? Copyright {
+ get => _copyright;
+ set => Assign (ImageStores.Copyright, value, markDirty: true);
+ }
+
+ ///
+ public override bool IsEmpty =>
+ base.IsEmpty
+ && string.IsNullOrEmpty (_description)
+ && string.IsNullOrEmpty (_copyright);
+
+ ///
+ public override BinaryData Render () => new (ImageRewrite.RenderTag (this));
+
+ ///
+ public override void Clear ()
+ {
+ DropUnmapped = true;
+ ClearStored (ImageStores.Title);
+ ClearStored (ImageStores.Artist);
+ ClearStored (ImageStores.Description);
+ ClearStored (ImageStores.Copyright);
+ ClearStored (ImageStores.Year);
+ ClearStored (ImageStores.Comment);
+ }
+
+ void ClearStored (ImageStores field)
+ {
+ if (Field (field) is null)
+ return;
+ Assign (field, null, markDirty: true);
+ }
+
+ void Assign (ImageStores field, string? value, bool markDirty)
+ {
+ if ((_stores & field) == 0)
+ return;
+ value = EmptyAsNull (value);
+ if (string.Equals (Field (field), value, StringComparison.Ordinal))
+ return;
+
+ switch (field) {
+ case ImageStores.Title:
+ _title = value;
+ break;
+ case ImageStores.Artist:
+ _artist = value;
+ break;
+ case ImageStores.Description:
+ _description = value;
+ break;
+ case ImageStores.Copyright:
+ _copyright = value;
+ break;
+ case ImageStores.Year:
+ _year = value;
+ break;
+ case ImageStores.Comment:
+ _comment = value;
+ break;
+ default:
+ return;
+ }
+
+ if (markDirty && (_stores & field) != 0)
+ _dirty |= field;
+ }
+
+ static string? EmptyAsNull (string? value) => string.IsNullOrEmpty (value) ? null : value;
+}
diff --git a/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs b/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs
new file mode 100644
index 00000000..9d4cf774
--- /dev/null
+++ b/src/TagLibSharp2/Image/Jpeg/JpegRewriter.cs
@@ -0,0 +1,496 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Text;
+using TagLibSharp2.Core;
+using TagLibSharp2.Image;
+using TagLibSharp2.Image.Exif;
+using TagLibSharp2.Image.Xmp;
+
+namespace TagLibSharp2.Image.Jpeg;
+
+///
+/// Reads a JPEG's COM segments and splices a new comment before the scan (ITU-T T.81 §B.2.4.5). Clear also drops
+/// the metadata APPn segments of every image a multi-picture index lists, and rewrites the index. Every byte from
+/// the scan on is copied as it is.
+///
+static class JpegRewriter
+{
+ const int MaxSegment = 65535;
+ internal const string SpliceError = "The JPEG marker list before the scan is truncated or malformed, so the comment cannot be spliced in.";
+
+ public static void Read (ReadOnlySpan data, ImageTag tag)
+ {
+ if (TryComment (data, out var text))
+ tag.ReadField (ImageStores.Comment, text);
+ }
+
+ /// The edited file as new pieces and ranges of .
+ public static ImagePlan? Plan (ReadOnlySpan data, ImageTag tag, out string? error)
+ {
+ error = null;
+ if (!tag.Changed (ImageStores.Comment) && !tag.DropUnmapped)
+ return null;
+ byte[]? replacement = tag.Changed (ImageStores.Comment)
+ ? tag.Field (ImageStores.Comment) is string comment ? EncodeComment (comment) : []
+ : null;
+ return TryRewrite (data, tag, replacement, out error);
+ }
+
+ static bool IsSoi (ReadOnlySpan data) => data.Length >= 2 && data[0] == 0xFF && data[1] == 0xD8;
+
+ static bool TryComment (ReadOnlySpan data, out string? text)
+ {
+ text = null;
+ if (!IsSoi (data))
+ return false;
+ var collected = new List ();
+ var i = 2;
+ while (i < data.Length) {
+ if (data[i] != 0xFF)
+ return collected.Count > 0;
+ while (i < data.Length && data[i] == 0xFF)
+ i++;
+ if (i >= data.Length)
+ return false;
+ var marker = data[i++];
+ if (marker is 0x01 or (>= 0xD0 and <= 0xD9)) {
+ if (marker == 0xD9)
+ break;
+ continue;
+ }
+
+ if (i + 1 >= data.Length)
+ return false;
+ var length = Endian.U16 (data, i, le: false);
+ if (length < 2 || i + length > data.Length)
+ return false;
+ if (marker == 0xDA)
+ break;
+ if (marker == 0xFE)
+ collected.AddRange (data.Slice (i + 2, length - 2).ToArray ());
+ i += length;
+ }
+
+ text = collected.Count == 0 ? null : Encoding.UTF8.GetString (collected.ToArray ());
+ return true;
+ }
+
+ static ImagePlan? TryRewrite (ReadOnlySpan data, ImageTag tag, byte[]? comment, out string? error)
+ {
+ error = null;
+ var dropMetadata = tag.DropUnmapped;
+ if (!IsSoi (data)) {
+ error = SpliceError;
+ return null;
+ }
+
+ // CIPA DC-007 §5.2: the first image's APP2 "MPF" index lists every image of a multi-picture file. Each
+ // later image is a whole JPEG with its own APPn after the first image's EOI; Clear cleans those too.
+ var index = MpfIndex.Read (data);
+ if (dropMetadata && index.Unreadable) {
+ error = "The JPEG MPF index cannot be read, so the metadata of the file's other images cannot be cleared.";
+ return null;
+ }
+
+ var images = dropMetadata ? index.Images : [];
+ if (!TryCleanLaterImages (data, images, tag, out var cleaned, out error))
+ return null;
+
+ // A version-65536 Apple gain map takes its headroom from the primary's maker note, so the later images are
+ // read first to know whether the primary keeps those two values (AppleHeadroom).
+ var options = new ImageOptions (comment, dropMetadata, Mirrors: comment is not null && !dropMetadata,
+ ItemLengths: dropMetadata ? cleaned.ConvertAll (c => c.Plan.Length) : null, AppleHeadroom: cleaned.Exists (c => c.HeadroomInMakerNote));
+ var primaryEnd = images.Count > 0 ? images[0].Start : data.Length;
+ var primary = RewriteImage (data.Slice (0, primaryEnd), tag, options, 0, out error);
+ if (primary is null)
+ return null;
+ if (primary.InMpf < 0)
+ return primary.Plan;
+ if (images.Count == 0)
+ return ShiftMpEntries (primary, data, out error);
+ return PlaceImages (data, primary, primaryEnd, images, cleaned, out error);
+ }
+
+ // The later images are cleaned first: an Ultra HDR primary lists their lengths (Item:Length).
+ static bool TryCleanLaterImages (ReadOnlySpan data, List images, ImageTag tag, out List cleaned, out string? error)
+ {
+ error = null;
+ cleaned = [];
+ var options = new ImageOptions ([], DropMetadata: true, Mirrors: false, ItemLengths: null, AppleHeadroom: false);
+ foreach (var image in images) {
+ if (RewriteImage (data.Slice (image.Start, image.Size), tag, options, image.Start, out _) is not JpegImage clean) {
+ error = $"Image {image.Entry + 1} of the JPEG MPF index cannot be parsed, so its metadata cannot be cleared.";
+ return false;
+ }
+
+ cleaned.Add (clean);
+ }
+
+ return true;
+ }
+
+ // Everything after the scan is copied, so the later images move with the bytes between the MP header and the
+ // scan, and image 1's size changes with everything before the scan.
+ static ImagePlan? ShiftMpEntries (JpegImage primary, ReadOnlySpan source, out string? error)
+ {
+ error = null;
+ var offsetDelta = (primary.OutRest - primary.OutMpf) - (long)(primary.InRest - primary.InMpf);
+ var sizeDelta = primary.OutRest - (long)primary.InRest;
+ if (offsetDelta == 0 && sizeDelta == 0)
+ return primary.Plan;
+ var count = primary.OutMpfEnd - primary.OutMpf;
+ var window = primary.Plan.MaterializeRange (primary.OutMpf, count, source);
+ if (!MpfIndex.TryRewriteEntries (window, 0, window.Length, (n, offset, size) => offset == 0 ? (0, size + sizeDelta) : (offset + offsetDelta, size))) {
+ error = "The JPEG MPF index cannot be read, so the offsets of its other images cannot be kept right after the edit.";
+ return null;
+ }
+
+ primary.Plan.Splice (primary.OutMpf, count, window);
+ return primary.Plan;
+ }
+
+ // The cleaned primary, then each cleaned later image in place of the old one with the bytes between copied, and
+ // every MP entry pointed at its image's new place.
+ static ImagePlan? PlaceImages (ReadOnlySpan data, JpegImage primary, int primaryEnd, List images, List cleaned, out string? error)
+ {
+ error = null;
+ var output = new ImagePlan ();
+ output.Append (primary.Plan);
+ var placed = new Dictionary ();
+ var at = primaryEnd;
+ for (var n = 0; n < images.Count; n++) {
+ var gap = images[n].Start - at;
+ if (gap > 0)
+ output.Copy (at, gap);
+ placed[images[n].Entry] = (output.Length, cleaned[n].Plan.Length);
+ output.Append (cleaned[n].Plan);
+ at = images[n].Start + images[n].Size;
+ }
+
+ if (at < data.Length)
+ output.Copy (at, data.Length - at);
+ var count = primary.OutMpfEnd - primary.OutMpf;
+ var window = output.MaterializeRange (primary.OutMpf, count, data);
+ var primaryDelta = primary.Plan.Length - primaryEnd;
+ var header = primary.OutMpf;
+ if (!MpfIndex.TryRewriteEntries (window, 0, window.Length, (n, offset, size) =>
+ placed.TryGetValue (n, out var image) ? (image.Start - header, image.Size) : offset == 0 ? (0, size + primaryDelta) : (offset, size))) {
+ error = "The JPEG MPF index cannot be read, so the offsets of its other images cannot be kept right after Clear.";
+ return null;
+ }
+
+ output.Splice (header, count, window);
+ return output;
+ }
+
+ // How one image is rewritten: the comment to add (null keeps the COM segments), whether its metadata is
+ // dropped (Clear), whether the APP1 copies of a changed comment are updated, the gain-map item lengths to
+ // write, and whether its first Exif keeps the Apple maker-note headroom.
+ sealed record ImageOptions (byte[]? Comment, bool DropMetadata, bool Mirrors, IReadOnlyList? ItemLengths, bool AppleHeadroom);
+
+ sealed class JpegImage
+ {
+ public ImagePlan Plan { get; init; } = new ();
+ public int InMpf { get; init; } = -1;
+ public int OutMpf { get; init; } = -1;
+ public int OutMpfEnd { get; init; } = -1;
+ public int InRest { get; init; }
+ public int OutRest { get; init; }
+ public bool HeadroomInMakerNote { get; init; }
+ }
+
+ // Rewrites the marker segments of one image up to its scan (or EOI), adds the new comment there, and copies
+ // the rest of the span as it is.
+ static JpegImage? RewriteImage (ReadOnlySpan data, ImageTag tag, ImageOptions options, int origin, out string? error)
+ {
+ error = null;
+ if (!IsSoi (data))
+ return Fail (out error);
+ var image = new ImageBuilder (tag, options, origin);
+ image.Keep (0, 2);
+ var i = 2;
+ while (i < data.Length) {
+ var start = i;
+ if (!TryMarker (data, ref i, out var marker))
+ return Fail (out error);
+
+ if (marker is 0x01 or (>= 0xD0 and <= 0xD8)) {
+ image.Keep (start, i - start);
+ continue;
+ }
+
+ if (marker == 0xD9)
+ return image.Finish (data, start, out error);
+ if (!TryLength (data, i, out var length))
+ return Fail (out error);
+
+ if (marker == 0xDA)
+ return image.Finish (data, start, out error);
+
+ // Fill bytes (0xFF) before the marker (T.81 §B.1.1.2) are part of what is kept or rewritten.
+ var segment = new Segment (marker, start, data.Slice (start, i - 2 - start), data.Slice (start, i + length - start), data.Slice (i + 2, length - 2));
+ i += length;
+ if (!image.TryAdd (segment, out error))
+ return null;
+ }
+
+ return image.Finish (data, data.Length, out error);
+ }
+
+ static JpegImage? Fail (out string? error)
+ {
+ error = SpliceError;
+ return null;
+ }
+
+ // At a 0xFF, skips the fill bytes and reads the marker; false when the byte is not 0xFF or the data ends.
+ static bool TryMarker (ReadOnlySpan data, ref int i, out byte marker)
+ {
+ marker = 0;
+ if (data[i] != 0xFF)
+ return false;
+ while (i < data.Length && data[i] == 0xFF)
+ i++;
+ if (i >= data.Length)
+ return false;
+ marker = data[i++];
+ return true;
+ }
+
+ // The segment length at i (it counts itself), when the segment lies inside the data.
+ static bool TryLength (ReadOnlySpan data, int i, out int length)
+ {
+ length = 0;
+ if (i + 1 >= data.Length)
+ return false;
+ length = Endian.U16 (data, i, le: false);
+ return length >= 2 && i + length <= data.Length;
+ }
+
+ // A marker segment: where it starts, the fill bytes before its marker, the whole segment and its payload.
+ readonly ref struct Segment (byte marker, int start, ReadOnlySpan fill, ReadOnlySpan whole, ReadOnlySpan payload)
+ {
+ public byte Marker { get; } = marker;
+ public int Start { get; } = start;
+ public ReadOnlySpan Fill { get; } = fill;
+ public ReadOnlySpan Whole { get; } = whole;
+ public ReadOnlySpan Payload { get; } = payload;
+ }
+
+ // The output of one image as its segments are kept, dropped or rewritten.
+ sealed class ImageBuilder (ImageTag tag, ImageOptions options, int origin)
+ {
+ readonly ImagePlan _plan = new ();
+ int _inMpf = -1;
+ int _outMpf = -1;
+ int _mpfLength;
+ bool _headroomInMakerNote;
+ bool _firstExif = true;
+
+ int Written => checked((int)_plan.Length);
+
+ public void Keep (int start, int count) => _plan.Copy (origin + (long)start, count);
+
+ public bool TryAdd (Segment segment, out string? error)
+ {
+ error = null;
+ var marker = segment.Marker;
+ var payload = segment.Payload;
+ if (options.DropMetadata && marker == 0xE1 && TryClearApp1 (segment))
+ return true;
+ if ((options.Comment is not null && marker == 0xFE) || (options.DropMetadata && marker is >= 0xE0 and <= 0xEF && !IsKeptOnClear (marker, payload)))
+ return true;
+ if (marker == 0xE2 && _inMpf < 0 && payload.StartsWith ("MPF\0"u8)) {
+ _inMpf = segment.Start + (segment.Whole.Length - payload.Length) + 4;
+ _outMpf = Written + (segment.Whole.Length - payload.Length) + 4;
+ _mpfLength = payload.Length - 4;
+ }
+
+ if (options.Mirrors && marker == 0xE1) {
+ if (!TryMirrorApp1 (payload, tag, out var edited, out error))
+ return false;
+ if (edited is not null) {
+ AddEdited (segment, edited);
+ return true;
+ }
+ }
+
+ Keep (segment.Start, segment.Whole.Length);
+ return true;
+ }
+
+ // Clear keeps only the gain-map XMP an HDR decoder needs (ImageGainMap), and of the first Exif (the one
+ // readers use) only the Apple maker-note headroom. True when the segment was handled (kept or dropped).
+ bool TryClearApp1 (Segment segment)
+ {
+ var payload = segment.Payload;
+ if (TryXmpSignature (payload, out var signature)) {
+ var kept = ImageGainMap.KeepForClear (payload.Slice (signature), options.ItemLengths, out var makerNote);
+ if (kept is null || 2 + signature + kept.Length > MaxSegment)
+ return true;
+ _headroomInMakerNote |= makerNote;
+ AddEdited (segment, SegmentBytes (0xE1, [.. payload.Slice (0, signature), .. kept]));
+ return true;
+ }
+
+ if (!payload.StartsWith ("Exif\0\0"u8) || !_firstExif)
+ return false;
+ _firstExif = false;
+ if (options.AppleHeadroom && AppleHeadroom.Keep (payload.Slice (6)) is byte[] headroom)
+ AddEdited (segment, SegmentBytes (0xE1, [.. "Exif\0\0"u8, .. headroom]));
+ return true;
+ }
+
+ void AddEdited (Segment segment, byte[] replacement)
+ {
+ if (!segment.Fill.IsEmpty)
+ _plan.Copy (origin + (long)segment.Start, segment.Fill.Length);
+ _plan.Add (replacement);
+ }
+
+ public JpegImage? Finish (ReadOnlySpan data, int rest, out string? error)
+ {
+ if (options.Comment is { Length: > 0 })
+ _plan.Add (options.Comment);
+ var outRest = Written;
+ _plan.Copy (origin + (long)rest, data.Length - rest);
+ error = null;
+ return Built (outRest, rest);
+ }
+
+ JpegImage Built (int outRest, int rest) => new () {
+ Plan = _plan,
+ InMpf = _inMpf,
+ OutMpf = _outMpf,
+ OutMpfEnd = _outMpf < 0 ? -1 : _outMpf + _mpfLength,
+ InRest = rest,
+ OutRest = outRest,
+ HeadroomInMakerNote = _headroomInMakerNote
+ };
+ }
+
+ // "http://ns.adobe.com/xap/1.0/" then NUL (XMP Part 3 §1.1.3), or with a space before the NUL as some writers
+ // do; exiftool and ImageIO read that packet too.
+ static bool TryXmpSignature (ReadOnlySpan payload, out int length)
+ {
+ length = payload.StartsWith ("http://ns.adobe.com/xap/1.0/\0"u8) ? 29 : payload.StartsWith ("http://ns.adobe.com/xap/1.0/ \0"u8) ? 30 : 0;
+ return length > 0;
+ }
+
+ // A Comment edit also changes the copies of the comment in APP1: Exif UserComment and XPComment, and XMP
+ // exif:UserComment. Extended XMP is spread over several segments and keyed by a digest of its content; when
+ // it may hold the comment, the save is refused rather than leave a stale copy.
+ static bool TryMirrorApp1 (ReadOnlySpan payload, ImageTag tag, out byte[]? edited, out string? error)
+ {
+ edited = null;
+ error = null;
+ if (payload.StartsWith ("Exif\0\0"u8)) {
+ var carrier = new ExifCarrier ("JPEG Exif", exif => SegmentBytes (0xE1, exif));
+ return carrier.TryEdit (payload, tag, out edited, out error);
+ }
+ if (TryXmpSignature (payload, out var signature))
+ return TryMirrorXmp (payload, signature, tag, out edited, out error);
+ if (payload.StartsWith ("http://ns.adobe.com/xmp/extension/\0"u8) && payload.IndexOf ("UserComment"u8) >= 0) {
+ error = "The JPEG extended XMP holds a UserComment, a copy of Comment that cannot be updated here.";
+ return false;
+ }
+
+ return true;
+ }
+
+ static bool TryMirrorXmp (ReadOnlySpan payload, int signature, ImageTag tag, out byte[]? edited, out string? error)
+ {
+ edited = null;
+ var packet = Encoding.UTF8.GetString (payload.Slice (signature));
+ if (!XmpMirror.TryUpdate (packet, tag, "JPEG XMP packet", out var updated, out error))
+ return false;
+ if (ReferenceEquals (updated, packet))
+ return true;
+ var bytes = Encoding.UTF8.GetBytes (updated);
+ if (2 + signature + bytes.Length > MaxSegment) {
+ error = "The JPEG XMP packet would no longer fit in one APP1 segment after the comment edit.";
+ return false;
+ }
+
+ var body = new byte[signature + bytes.Length];
+ payload.Slice (0, signature).CopyTo (body);
+ bytes.CopyTo (body, signature);
+ edited = SegmentBytes (0xE1, body);
+ return true;
+ }
+
+ static byte[] SegmentBytes (byte marker, byte[] payload)
+ {
+ var segment = new byte[4 + payload.Length];
+ segment[0] = 0xFF;
+ segment[1] = marker;
+ segment[2] = (byte)((payload.Length + 2) >> 8);
+ segment[3] = (byte)(payload.Length + 2);
+ payload.CopyTo (segment, 4);
+ return segment;
+ }
+
+ // Clear drops every APPn segment except the ones a decoder or colour management needs, or that carry the
+ // file's structure:
+ // - APP0 "JFIF" and "JFXX" (JFIF 1.02: pixel density and the format of the file, and its thumbnail);
+ // - APP2 "ICC_PROFILE" (ICC.1 Annex B.4: the colour profile);
+ // - APP2 "MPF" (CIPA DC-007 §5.2: the index of the images of a multi-picture file, and their attributes);
+ // - APP2 "urn:iso:std:iso:ts:21496:-1" (ISO 21496-1: the gain map version and parameters an HDR decoder
+ // applies to the gain-map image);
+ // - APP14 "Adobe" (the colour transform flag that says whether the components are YCbCr or YCCK);
+ // - APP11 JPEG XT boxes a JPEG XT decoder uses to rebuild the image. Each APP11 segment holds "JP", the box
+ // instance En, the sequence number Z, then the box's LBox and TBox, repeated in every segment of a box
+ // (ISO/IEC 18477-3 Annex A). The decoding boxes are those named in A. Artusi et al., "JPEG XT: A Compression
+ // Standard for HDR and WCG Images", IEEE Signal Processing Magazine 33(2), 2016, §III and Fig. 3: ftyp (file
+ // type), TONE (inverse tone mapping), RTRF and LTRF (residual and base colour transforms), LCHK (legacy data
+ // checksum), SPEC (the superbox that says how to reassemble the image) and RESI (the residual codestream).
+ // A legacy decoder skips every APP11 box (same paper, §III), so the base image never needs them. Every other
+ // box goes: JUMBF superboxes "jumb" (ISO/IEC 19566-5: C2PA, JSON, XML), "xml ", "uuid", "json", "Exif", and
+ // unknown types. (Annex B of 18477-3, the full box list, is not public; refinement and alpha boxes are not
+ // named there and are dropped.)
+ // Exif (but for the Apple maker-note headroom a version-65536 gain map needs, AppleHeadroom), XMP and extended
+ // XMP, Photoshop/IPTC, Ducky, FlashPix, maker segments such as SCALADO, and unknown APPn are dropped. Segments
+ // other than APPn (tables, frame, restart interval) are kept.
+ static bool IsKeptOnClear (byte marker, ReadOnlySpan payload) => marker switch {
+ 0xE0 => payload.StartsWith ("JFIF\0"u8) || payload.StartsWith ("JFXX\0"u8),
+ 0xE2 => payload.StartsWith ("ICC_PROFILE\0"u8) || payload.StartsWith ("MPF\0"u8) || payload.StartsWith ("urn:iso:std:iso:ts:21496:-1\0"u8),
+ 0xEB => payload.Length >= 16 && payload[0] == (byte)'J' && payload[1] == (byte)'P' && IsXtDecodingBox (payload.Slice (12, 4)),
+ 0xEE => payload.StartsWith ("Adobe"u8),
+ _ => false
+ };
+
+ static readonly string[] XtDecodingBoxes = ["ftyp", "TONE", "RTRF", "LTRF", "LCHK", "SPEC", "RESI"];
+
+ static bool IsXtDecodingBox (ReadOnlySpan type)
+ {
+ foreach (var box in XtDecodingBoxes) {
+ if (type[0] == box[0] && type[1] == box[1] && type[2] == box[2] && type[3] == box[3])
+ return true;
+ }
+
+ return false;
+ }
+
+ /// COM segments of at most 65,533 bytes each, split between UTF-8 sequences.
+ public static byte[] EncodeComment (string comment)
+ {
+ var bytes = Encoding.UTF8.GetBytes (comment);
+ using var builder = new BinaryDataBuilder (bytes.Length + 8);
+ var offset = 0;
+ while (offset < bytes.Length) {
+ var take = Math.Min (65533, bytes.Length - offset);
+ while (take > 0 && offset + take < bytes.Length && (bytes[offset + take] & 0xC0) == 0x80)
+ take--;
+ if (take == 0)
+ take = Math.Min (65533, bytes.Length - offset);
+ builder.Add (0xFF);
+ builder.Add (0xFE);
+ builder.AddUInt16BE ((ushort)(take + 2));
+ builder.Add (bytes.AsSpan (offset, take));
+ offset += take;
+ }
+
+ return builder.ToArray ();
+ }
+}
diff --git a/src/TagLibSharp2/Image/Jpeg/JpegSize.cs b/src/TagLibSharp2/Image/Jpeg/JpegSize.cs
new file mode 100644
index 00000000..e0a28c73
--- /dev/null
+++ b/src/TagLibSharp2/Image/Jpeg/JpegSize.cs
@@ -0,0 +1,140 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Core;
+using TagLibSharp2.Image;
+
+namespace TagLibSharp2.Image.Jpeg;
+
+///
+/// The width, height and bit depth of a JPEG: the first start-of-frame segment (ITU-T T.81 §B.2.2), or with a zero
+/// height, the DNL segment after the first scan (§B.2.5).
+///
+static class JpegSize
+{
+ public static bool IsJpeg (ReadOnlySpan data) =>
+ data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF;
+
+ public static bool TryRead (ReadOnlySpan data, out ImageProperties? properties)
+ {
+ properties = null;
+ if (!IsJpeg (data))
+ return false;
+ var i = 2;
+ Frame? pending = null;
+ while (TryNextSegment (data, ref i, out var marker, out var length)) {
+ if (IsStartOfFrame (marker)) {
+ if (!TryFrame (data.Slice (i, length), out var frame))
+ return false;
+ if (frame.Height > 0) {
+ properties = frame.Properties (frame.Height);
+ return true;
+ }
+
+ // ITU-T T.81 §B.2.2: a zero height is defined by the DNL segment at the end of the first scan.
+ pending = frame;
+ } else if (marker == 0xDA) {
+ if (pending is not Frame waiting || !TryDnlHeight (data, i + length, out var lines))
+ return false;
+ properties = waiting.Properties (lines);
+ return true;
+ }
+
+ i += length;
+ }
+
+ return false;
+ }
+
+ // The next marker segment at i, past fill bytes and RSTn: its marker, and i at its length field. False at a
+ // byte that is not a marker, at SOI or EOI, or when the segment runs past the data.
+ static bool TryNextSegment (ReadOnlySpan data, ref int i, out byte marker, out int length)
+ {
+ marker = 0;
+ length = 0;
+ while (i + 1 < data.Length) {
+ if (data[i] != 0xFF)
+ return false;
+ while (i < data.Length && data[i] == 0xFF)
+ i++;
+ if (i >= data.Length)
+ return false;
+ marker = data[i++];
+ if (marker is 0xD8 or 0xD9)
+ return false;
+ if (marker is >= 0xD0 and <= 0xD7)
+ continue;
+ if (i + 1 >= data.Length)
+ return false;
+ length = Endian.U16 (data, i, le: false);
+ return length >= 2 && i + length <= data.Length;
+ }
+
+ return false;
+ }
+
+ readonly record struct Frame (int Width, int Height, int Precision, int Components)
+ {
+ public ImageProperties Properties (int height)
+ {
+ var depth = Precision;
+ if (Components is >= 1 and <= 4 && Precision <= int.MaxValue / Components)
+ depth = Precision * Components;
+ return new ImageProperties (Width, height, depth, "JPEG");
+ }
+ }
+
+ // A start-of-frame segment from its length field: precision, height, width, then the component count.
+ static bool TryFrame (ReadOnlySpan segment, out Frame frame)
+ {
+ frame = default;
+ if (segment.Length < 7)
+ return false;
+ var height = Endian.U16 (segment, 3, le: false);
+ var width = Endian.U16 (segment, 5, le: false);
+ if (width <= 0 || height < 0)
+ return false;
+ var components = segment.Length >= 8 && segment[7] is >= 1 and <= 4 ? segment[7] : 1;
+ frame = new Frame (width, height, segment[2], components);
+ return true;
+ }
+
+ // ITU-T T.81 §B.2.5: a DNL segment "shall immediately follow the first scan". The scan's entropy-coded data
+ // (§B.1.1.5) holds no marker: a 0xFF data byte is followed by a stuffed 0x00, and RSTn (0xD0-0xD7) may sit
+ // between intervals. Fill bytes 0xFF may precede a marker (§B.1.1.2). Any other marker before DNL means
+ // there is none. One pass over the bytes present.
+ static bool TryDnlHeight (ReadOnlySpan data, int scan, out int lines)
+ {
+ lines = 0;
+ var i = scan;
+ while (i < data.Length) {
+ if (data[i] != 0xFF) {
+ i++;
+ continue;
+ }
+
+ while (i < data.Length && data[i] == 0xFF)
+ i++;
+ if (i >= data.Length)
+ return false;
+ var marker = data[i++];
+ if (marker == 0x00 || marker is >= 0xD0 and <= 0xD7)
+ continue;
+ if (marker != 0xDC || i + 3 >= data.Length)
+ return false;
+ var length = Endian.U16 (data, i, le: false);
+ if (length != 4)
+ return false;
+ lines = Endian.U16 (data, i + 2, le: false);
+ return lines > 0;
+ }
+
+ return false;
+ }
+
+ static bool IsStartOfFrame (byte marker) =>
+ marker is 0xC0 or 0xC1 or 0xC2 or 0xC3
+ or 0xC5 or 0xC6 or 0xC7
+ or 0xC9 or 0xCA or 0xCB
+ or 0xCD or 0xCE or 0xCF;
+}
diff --git a/src/TagLibSharp2/Image/Jpeg/MpfIndex.cs b/src/TagLibSharp2/Image/Jpeg/MpfIndex.cs
new file mode 100644
index 00000000..30ec1871
--- /dev/null
+++ b/src/TagLibSharp2/Image/Jpeg/MpfIndex.cs
@@ -0,0 +1,149 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Image;
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image.Jpeg;
+
+/// One later image of a multi-picture file: its MP entry number, where it starts and its size.
+readonly record struct MpImage (int Entry, int Start, int Size);
+
+///
+/// The first image's MP index (CIPA DC-007 §5.2.3.3): an MP Entry per image, each 16 bytes of attribute, size,
+/// and offset from the MP header (0 for the first image). The MP index IFD and its entry list are a TIFF structure
+/// inside the APP2 "MPF" segment, read with over that segment's bytes.
+///
+sealed class MpfIndex
+{
+ const int MpEntryTag = 0xB002;
+
+ public bool Unreadable { get; init; }
+ public List Images { get; init; } = [];
+
+ ///
+ /// The later images, sorted. For Clear, every later image must be a whole JPEG inside the file, after the first
+ /// image's end (its EOI), without overlapping another; otherwise the index is unreadable.
+ ///
+ public static MpfIndex Read (ReadOnlySpan data)
+ {
+ if (FindHeader (data) is not var (header, limit, firstEnd))
+ return new MpfIndex ();
+ var entries = new List<(long Offset, long Size)> ();
+ if (!TryReadEntries (data, header, limit, entries))
+ return new MpfIndex { Unreadable = true };
+ var images = new List ();
+ for (var n = 0; n < entries.Count; n++) {
+ var (offset, size) = entries[n];
+ if (offset == 0)
+ continue;
+ var start = header + offset;
+ if (start < firstEnd || size < 4 || start + size > data.Length || data[(int)start] != 0xFF || data[(int)start + 1] != 0xD8)
+ return new MpfIndex { Unreadable = true };
+ images.Add (new MpImage (n, (int)start, (int)size));
+ }
+
+ images.Sort ((a, b) => a.Start.CompareTo (b.Start));
+ for (var n = 1; n < images.Count; n++) {
+ if (images[n].Start < images[n - 1].Start + images[n - 1].Size)
+ return new MpfIndex { Unreadable = true };
+ }
+
+ return new MpfIndex { Images = images };
+ }
+
+ // The MP header of the first APP2 "MPF" segment, the end of that segment's payload, and where the first image
+ // ends (a later image cannot start before it); null without an MPF segment before the scan.
+ static (int Header, int Limit, int Scan)? FindHeader (ReadOnlySpan data)
+ {
+ (int Header, int Limit)? found = null;
+ var i = 2;
+ while (i + 4 <= data.Length && data[i] == 0xFF) {
+ var marker = data[i + 1];
+ if (marker is 0xDA or 0xD9)
+ return found is var (header, limit) ? (header, limit, FirstImageEnd (data, i)) : null;
+ if (marker is 0x01 or (>= 0xD0 and <= 0xD8) or 0xFF) {
+ i += marker == 0xFF ? 1 : 2;
+ continue;
+ }
+
+ var length = Endian.U16 (data, i + 2, le: false);
+ if (length < 2 || i + 2 + length > data.Length)
+ break;
+ if (marker == 0xE2 && data.Slice (i + 4, length - 2).StartsWith ("MPF\0"u8))
+ found ??= (i + 8, i + 2 + length);
+ i += 2 + length;
+ }
+
+ return found is var (h, l) ? (h, l, data.Length) : null;
+ }
+
+ // The end of the first image: after its EOI, the first FF D9 from its first scan on (entropy-coded data holds no
+ // FF D9: an FF there is followed by 00 or a restart marker); the data's end without one.
+ static int FirstImageEnd (ReadOnlySpan data, int scan) =>
+ data.Slice (scan).IndexOf (Eoi) is var eoi and >= 0 ? scan + eoi + 2 : data.Length;
+
+ static ReadOnlySpan Eoi => [0xFF, 0xD9];
+
+ static bool TryReadEntries (ReadOnlySpan data, int header, int limit, List<(long Offset, long Size)> entries)
+ {
+ if (!TryEntryList (data, header, limit, out var le, out var list, out var count))
+ return false;
+ for (var n = 0; n < count; n++) {
+ var at = (int)list + (16 * n);
+ entries.Add ((Endian.U32 (data, at + 8, le), Endian.U32 (data, at + 4, le)));
+ }
+
+ return true;
+ }
+
+ /// Rewrites every MP entry's offset and size with update (entry number, offset, size).
+ public static bool TryRewriteEntries (byte[] output, int header, int limit, Func update)
+ {
+ if (!TryEntryList (output, header, limit, out var le, out var list, out var count))
+ return false;
+ var span = output.AsSpan ();
+ for (var n = 0; n < count; n++) {
+ var at = (int)list + (16 * n);
+ var (offset, size) = update (n, Endian.U32 (span, at + 8, le), Endian.U32 (span, at + 4, le));
+ if (offset < 0 || offset > uint.MaxValue || size < 0 || size > uint.MaxValue)
+ return false;
+ Endian.WriteU32 (span, at + 8, offset, le);
+ Endian.WriteU32 (span, at + 4, size, le);
+ }
+
+ return true;
+ }
+
+ // CIPA DC-007 §5.2: the MP index IFD and the MP entry list it points to are inside the APP2 segment. An index
+ // that points outside it is unreadable: following it would read or overwrite other bytes. The list is where the
+ // entries start in the file; count 0 when the index has no MP Entry tag. The header and the segment's end are
+ // where the segment was found in these bytes.
+ static bool TryEntryList (ReadOnlySpan data, int header, int limit, out bool le, out long list, out int count)
+ {
+ (le, list, count) = (default, 0, 0);
+ if (header + 8 > limit)
+ return false;
+ var segment = data.Slice (header, limit - header);
+ if (!TiffReader.TryByteOrder (segment, out le))
+ return false;
+ var tiff = new TiffReader (segment, le);
+ var ifd = tiff.U32 (4);
+ if (!tiff.TryTable (ifd, out var tags))
+ return false;
+ for (var n = 0; n < tags; n++) {
+ var entry = tiff.Entry (ifd, n);
+ if (tiff.Tag (entry) != MpEntryTag)
+ continue;
+ var bytes = tiff.Count (entry);
+ var at = tiff.Value (entry);
+ list = header + at;
+ if (bytes % 16 != 0 || at < TiffReader.HeaderSize || at + bytes > segment.Length)
+ return false;
+ count = (int)(bytes / 16);
+ return true;
+ }
+
+ return true;
+ }
+}
diff --git a/src/TagLibSharp2/Image/MirrorFields.cs b/src/TagLibSharp2/Image/MirrorFields.cs
new file mode 100644
index 00000000..33f799dd
--- /dev/null
+++ b/src/TagLibSharp2/Image/MirrorFields.cs
@@ -0,0 +1,54 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+namespace TagLibSharp2.Image;
+
+///
+/// The fields an image tag stores whose copies other blocks of the same file hold, and where each copy is. macOS
+/// ImageIO shows the XMP (dc:title, dc:creator, dc:description, dc:rights) and the Exif
+/// IFD0 values (ImageDescription, Artist, Copyright) in preference to PNG text, so an edit that
+/// left them would not show there.
+///
+///
+/// XMP: Adobe XMP Specification Part 1 §7.9 (language alternatives, rdf:Alt with x-default) and §8.2.2.4
+/// (Dublin Core: title, description and rights are Lang Alt, creator is an ordered array). Exif: CIPA DC-008 (Exif
+/// 2.32) §4.6.4 Table 4 (IFD0 tags 0x010E, 0x013B, 0x8298) and §4.6.5 (UserComment 0x9286 in the Exif IFD, reached
+/// through tag 0x8769). The Windows XP tags 0x9C9B-0x9C9D are read by Windows and exiftool as title, comment and
+/// author. Text: the keywords exiftool and ImageMagick write for the same fields.
+///
+static class MirrorFields
+{
+ internal const string DcNamespace = "http://purl.org/dc/elements/1.1/";
+ internal const string ExifNamespace = "http://ns.adobe.com/exif/1.0/";
+
+ internal static readonly MirrorField[] All = [
+ new (ImageStores.Title, "Title", DcNamespace, "title", ordered: false, ifd0: [0x9C9B], exifIfd: [], text: []),
+ new (ImageStores.Artist, "Artist", DcNamespace, "creator", ordered: true, ifd0: [0x013B, 0x9C9D], exifIfd: [], text: ["exif:Artist", "Artist"]),
+ new (ImageStores.Description, "Description", DcNamespace, "description", ordered: false, ifd0: [0x010E], exifIfd: [], text: ["exif:ImageDescription"]),
+ new (ImageStores.Copyright, "Copyright", DcNamespace, "rights", ordered: false, ifd0: [0x8298], exifIfd: [], text: ["exif:Copyright"]),
+ new (ImageStores.Comment, "Comment", ExifNamespace, "UserComment", ordered: false, ifd0: [0x9C9C], exifIfd: [0x9286], text: ["exif:UserComment"]),
+ ];
+
+ internal static bool AnyChanged (ImageTag tag)
+ {
+ foreach (var field in All) {
+ if (tag.Changed (field.Store))
+ return true;
+ }
+
+ return false;
+ }
+
+
+ internal sealed class MirrorField (ImageStores store, string name, string xmpNamespace, string xmpName, bool ordered, int[] ifd0, int[] exifIfd, string[] text)
+ {
+ public ImageStores Store { get; } = store;
+ public string Name { get; } = name;
+ public string XmpNamespace { get; } = xmpNamespace;
+ public string XmpName { get; } = xmpName;
+ public bool Ordered { get; } = ordered;
+ public int[] Ifd0 { get; } = ifd0;
+ public int[] ExifIfd { get; } = exifIfd;
+ public string[] Text { get; } = text;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Png/PngChunks.cs b/src/TagLibSharp2/Image/Png/PngChunks.cs
new file mode 100644
index 00000000..879c6652
--- /dev/null
+++ b/src/TagLibSharp2/Image/Png/PngChunks.cs
@@ -0,0 +1,76 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using TagLibSharp2.Core;
+
+namespace TagLibSharp2.Image.Png;
+
+/// A chunk of a PNG file: where it starts and its whole length (length, type, data and CRC).
+readonly struct PngChunk (int start, int length)
+{
+ public int Start { get; } = start;
+ public int Length { get; } = length;
+}
+
+/// The chunk list of a PNG file (PNG 3rd ed. §5.3): walking it, checking a CRC, and writing a chunk.
+static class PngChunks
+{
+ /// The chunks from the signature up to IEND or the first chunk that runs past the data.
+ public static bool TryWalk (ReadOnlySpan data, out List chunks)
+ {
+ chunks = [];
+ if (data.Length < 8 || data[0] != 0x89 || data[1] != (byte)'P' || data[2] != (byte)'N' || data[3] != (byte)'G'
+ || data[4] != 0x0D || data[5] != 0x0A || data[6] != 0x1A || data[7] != 0x0A)
+ return false;
+ var i = 8;
+ while (i + 12 <= data.Length) {
+ var length = ReadLength (data, i);
+ if (length < 0 || i + 12L + length > data.Length)
+ break;
+ var size = 12 + length;
+ chunks.Add (new PngChunk (i, size));
+ if (data.Slice (i + 4, 4).SequenceEqual ("IEND"u8))
+ break;
+ i += size;
+ }
+
+ return true;
+ }
+
+ public static bool IsTextChunk (ReadOnlySpan type) =>
+ type.SequenceEqual ("tEXt"u8) || type.SequenceEqual ("zTXt"u8) || type.SequenceEqual ("iTXt"u8);
+
+ public static bool TypeEquals (ReadOnlySpan data, PngChunk chunk, ReadOnlySpan type) =>
+ data.Slice (chunk.Start + 4, 4).SequenceEqual (type);
+
+ public static bool CrcMatches (ReadOnlySpan chunk)
+ {
+ var length = chunk.Length - 12;
+ return BinaryData.ComputeCrc32 (chunk.Slice (4, 4 + length)) == (uint)Endian.U32 (chunk, 8 + length, le: false);
+ }
+
+ /// A chunk length field, or -1 above 2^31 - 1 (PNG 3rd ed. §5.3).
+ public static int ReadLength (ReadOnlySpan data, int offset)
+ {
+ var value = Endian.U32 (data, offset, le: false);
+ return value > int.MaxValue ? -1 : (int)value;
+ }
+
+ public static void Add (BinaryDataBuilder builder, ReadOnlySpan type, byte[] payload)
+ {
+ builder.AddUInt32BE ((uint)payload.Length);
+ builder.Add (type);
+ builder.Add (payload);
+ var crcInput = new byte[4 + payload.Length];
+ type.CopyTo (crcInput);
+ payload.CopyTo (crcInput, 4);
+ builder.AddUInt32BE (new BinaryData (crcInput).ComputeCrc32 ());
+ }
+
+ public static byte[] Chunk (ReadOnlySpan type, byte[] payload)
+ {
+ using var builder = new BinaryDataBuilder (payload.Length + 12);
+ Add (builder, type, payload);
+ return builder.ToArray ();
+ }
+}
diff --git a/src/TagLibSharp2/Image/Png/PngKeywords.cs b/src/TagLibSharp2/Image/Png/PngKeywords.cs
new file mode 100644
index 00000000..1257960c
--- /dev/null
+++ b/src/TagLibSharp2/Image/Png/PngKeywords.cs
@@ -0,0 +1,48 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+namespace TagLibSharp2.Image.Png;
+
+///
+/// The PNG text keywords of the tag's fields (PNG 3rd ed. §11.3.3.2 predefined keywords), and the keywords other
+/// writers copy a field into: exiftool's "Artist", and ImageMagick's exif:* text.
+///
+static class PngKeywords
+{
+ /// exiftool writes its Artist tag to a PNG as this keyword; "Author" wins when both are present.
+ internal const string ExiftoolArtist = "Artist";
+
+ public static ImageStores FieldFor (string keyword) => keyword switch {
+ "Title" => ImageStores.Title,
+ "Author" => ImageStores.Artist,
+ "Description" => ImageStores.Description,
+ "Copyright" => ImageStores.Copyright,
+ "Creation Time" => ImageStores.Year,
+ "Comment" => ImageStores.Comment,
+ _ => ImageStores.None
+ };
+
+ public static string Keyword (ImageStores field) => field switch {
+ ImageStores.Artist => "Author",
+ ImageStores.Description => "Description",
+ ImageStores.Copyright => "Copyright",
+ ImageStores.Year => "Creation Time",
+ ImageStores.Comment => "Comment",
+ _ => "Title"
+ };
+
+ /// A text keyword that copies a changed field (ImageMagick writes these as plain tEXt).
+ public static bool IsMirror (string keyword, ImageTag tag)
+ {
+ foreach (var field in MirrorFields.All) {
+ if (!tag.Changed (field.Store))
+ continue;
+ foreach (var text in field.Text) {
+ if (string.Equals (text, keyword, StringComparison.Ordinal))
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Png/PngRewriter.cs b/src/TagLibSharp2/Image/Png/PngRewriter.cs
new file mode 100644
index 00000000..fd63f263
--- /dev/null
+++ b/src/TagLibSharp2/Image/Png/PngRewriter.cs
@@ -0,0 +1,308 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Text;
+using TagLibSharp2.Core;
+using TagLibSharp2.Image.Exif;
+using TagLibSharp2.Image.Xmp;
+
+namespace TagLibSharp2.Image.Png;
+
+///
+/// Reads a PNG's text fields and splices edited text into its chunk list: new text before the pixel data, changed
+/// keywords dropped, and the XMP and Exif copies of a changed field updated. Every other chunk, and anything after
+/// IEND, is copied as it is.
+///
+static class PngRewriter
+{
+ internal const string SpliceError = "The PNG chunk list does not reach IEND, so the text cannot be spliced in.";
+
+ const string XmpKeyword = "XML:com.adobe.xmp";
+ const string RawXmpKeyword = "Raw profile type xmp";
+ const string RawExifKeyword = "Raw profile type exif";
+ const string RawApp1Keyword = "Raw profile type APP1";
+
+ // Clear keeps what a decoder or colour management needs to show the pixels and drops every other
+ // ancillary chunk (rule 7: mapped and unmapped, known and unknown). Kept:
+ // - every critical chunk (PNG 3rd ed. §5.4: an uppercase first letter; a decoder must understand it);
+ // - tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT (§11.3.1-§11.3.2: transparency, colour space,
+ // HDR mastering and content light level, significant bits);
+ // - bKGD, hIST, pHYs, sPLT (§11.3.5: background, palette histogram, pixel aspect, suggested palette);
+ // - acTL, fcTL, fdAT (§11.3.6: APNG animation; fdAT holds frame pixels);
+ // - oFFs, pCAL, sCAL, sTER (PNG Extensions 1.6.0: position, pixel calibration, scale, stereo layout).
+ // Dropped include tEXt, zTXt, iTXt (XMP and ImageMagick's raw EXIF/IPTC/XMP profiles), eXIf, zxIf, tIME,
+ // caBX (a C2PA manifest, which any edit invalidates: C2PA 2.1 §14.3.3), dSIG, and Apple's iDOT.
+ static readonly string[] KeptOnClear = [
+ "tRNS", "gAMA", "cHRM", "sRGB", "iCCP", "cICP", "mDCV", "cLLI", "sBIT",
+ "bKGD", "hIST", "pHYs", "sPLT", "acTL", "fcTL", "fdAT", "oFFs", "pCAL", "sCAL", "sTER",
+ ];
+
+ static readonly ImageStores[] TextFields = [
+ ImageStores.Title, ImageStores.Artist, ImageStores.Description, ImageStores.Copyright, ImageStores.Year, ImageStores.Comment,
+ ];
+
+ public static void Read (ReadOnlySpan data, ImageTag tag)
+ {
+ if (!PngChunks.TryWalk (data, out var chunks))
+ return;
+ var budget = PngText.MaxInflatedText;
+ string? artist = null;
+ foreach (var chunk in chunks)
+ ReadChunk (data.Slice (chunk.Start, chunk.Length), tag, ref budget, ref artist);
+
+ // exiftool writes its Artist tag to a PNG as the keyword "Artist". PNG 3rd ed. §11.3.3.2 predefines
+ // "Author" for the same field, which wins when both are present.
+ if (tag.Artist is null && artist is not null)
+ tag.ReadField (ImageStores.Artist, artist);
+ }
+
+ static void ReadChunk (ReadOnlySpan chunk, ImageTag tag, ref int budget, ref string? artist)
+ {
+ if (chunk.Length < 12)
+ return;
+ var length = PngChunks.ReadLength (chunk, 0);
+ if (length < 0 || 12 + length != chunk.Length)
+ return;
+ var type = chunk.Slice (4, 4);
+ if (!PngChunks.IsTextChunk (type) || !PngChunks.CrcMatches (chunk))
+ return;
+ var payload = chunk.Slice (8, length);
+ if (!PngText.TryKeyword (payload, out var keyword, out var rest))
+ return;
+ var field = PngKeywords.FieldFor (keyword);
+ if (field == ImageStores.None && keyword != PngKeywords.ExiftoolArtist)
+ return;
+ if (!PngText.TryText (type, payload.Slice (rest), ref budget, out var text))
+ return;
+ if (field == ImageStores.None)
+ artist = string.IsNullOrEmpty (text) ? artist : text;
+ else
+ tag.ReadField (field, text);
+ }
+
+ /// Every text field (or only the changed ones) as new text chunks, in a fixed order.
+ public static void AddFields (BinaryDataBuilder builder, ImageTag tag, bool onlyChanged)
+ {
+ foreach (var field in TextFields) {
+ if ((onlyChanged && !tag.Changed (field)) || tag.Field (field) is not string value)
+ continue;
+ PngText.Add (builder, PngKeywords.Keyword (field), value);
+ }
+ }
+
+ /// The edited file as new pieces and ranges of .
+ public static ImagePlan? Plan (ReadOnlySpan data, ImageTag tag, out string? error)
+ {
+ error = null;
+ var walked = PngChunks.TryWalk (data, out var chunks);
+ var ends = walked && chunks.Count > 0 && PngChunks.TypeEquals (data, chunks[^1], "IEND"u8);
+ if (!ends) {
+ error = SpliceError;
+ return null;
+ }
+
+ return CopyChunks (data, chunks, tag, Layout.Of (data, chunks), out error);
+ }
+
+ // Where new text goes: before the pixel data, and before Apple's iDOT, which records where the IDAT chunks are.
+ readonly record struct Layout (int Insert, int Idot, int Idat)
+ {
+ public static Layout Of (ReadOnlySpan data, List chunks)
+ {
+ var insert = chunks[^1].Start;
+ var idot = -1;
+ var idat = -1;
+ foreach (var chunk in chunks) {
+ if (PngChunks.TypeEquals (data, chunk, "IDAT"u8)) {
+ idat = chunk.Start;
+ insert = idot >= 0 ? idot : chunk.Start;
+ break;
+ }
+
+ if (PngChunks.TypeEquals (data, chunk, "iDOT"u8))
+ idot = chunk.Start;
+ }
+
+ return new Layout (insert, idot, idat);
+ }
+ }
+
+ static ImagePlan? CopyChunks (
+ ReadOnlySpan data,
+ List chunks,
+ ImageTag tag,
+ Layout layout,
+ out string? error)
+ {
+ error = null;
+ var plan = new ImagePlan ();
+ var mirrors = !tag.DropUnmapped && MirrorFields.AnyChanged (tag);
+ // One inflation budget for every compressed copy in the file, as when it is read.
+ var budget = PngText.MaxInflatedText;
+ long outIdot = -1;
+ long outIdat = -1;
+ var copiedIdot = false;
+ plan.Copy (0, 8);
+ foreach (var chunk in chunks) {
+ if (chunk.Start == layout.Insert)
+ plan.Add (ChangedFields (tag));
+ if (chunk.Start == layout.Idot)
+ outIdot = plan.Length;
+ if (chunk.Start == layout.Idat)
+ outIdat = plan.Length;
+ if (IsDropped (data, chunk, tag))
+ continue;
+ byte[]? edited = null;
+ var whole = data.Slice (chunk.Start, chunk.Length);
+ if (mirrors && !TryMirrorChunk (whole, tag, ref budget, out edited, out error))
+ return null;
+ if (edited is not null) {
+ plan.Add (edited);
+ continue;
+ }
+
+ if (chunk.Start == layout.Idot)
+ copiedIdot = true;
+ plan.Copy (chunk.Start, chunk.Length);
+ }
+
+ // PNG 3rd ed. §5.6: IEND is the last chunk. Whatever follows it (an appended archive, padding) is not
+ // the PNG's to change, so it is copied as it is.
+ var tail = chunks[^1].Start + chunks[^1].Length;
+ plan.Copy (tail, data.Length - tail);
+ DropStaleIdot (plan, data, layout, outIdot, outIdat, copiedIdot);
+ return plan;
+ }
+
+ static byte[] ChangedFields (ImageTag tag)
+ {
+ using var builder = new BinaryDataBuilder ();
+ AddFields (builder, tag, onlyChanged: true);
+ return builder.ToArray ();
+ }
+
+ // iDOT holds the offset of the IDAT data from itself. When a chunk between them changed, the offset is wrong,
+ // so iDOT is dropped (a decoder then reads the IDAT chunks in order, as it does for any PNG).
+ static void DropStaleIdot (
+ ImagePlan plan,
+ ReadOnlySpan data,
+ Layout layout,
+ long outIdot,
+ long outIdat,
+ bool copiedIdot)
+ {
+ var kept = copiedIdot && outIdot >= 0 && outIdot + 8 <= plan.Length && IsIdot (data, layout.Idot);
+ if (!kept || layout.Idat < 0 || outIdat - outIdot == layout.Idat - layout.Idot)
+ return;
+ var length = PngChunks.ReadLength (data, layout.Idot);
+ if (length < 0)
+ return;
+ plan.Cut (outIdot, 12L + length);
+ }
+
+ static bool IsIdot (ReadOnlySpan data, int start) =>
+ data.Slice (start + 4, 4).SequenceEqual ("iDOT"u8);
+
+ static bool IsKeptOnClear (ReadOnlySpan type)
+ {
+ if ((type[0] & 0x20) == 0)
+ return true;
+ foreach (var kept in KeptOnClear) {
+ if (type[0] == kept[0] && type[1] == kept[1] && type[2] == kept[2] && type[3] == kept[3])
+ return true;
+ }
+
+ return false;
+ }
+
+ static bool IsDropped (ReadOnlySpan data, PngChunk chunk, ImageTag tag)
+ {
+ var type = data.Slice (chunk.Start + 4, 4);
+ if (tag.DropUnmapped)
+ return !IsKeptOnClear (type);
+ if (!PngChunks.IsTextChunk (type))
+ return false;
+ var payload = data.Slice (chunk.Start + 8, chunk.Length - 12);
+ if (!PngText.TryKeyword (payload, out var keyword, out _))
+ return false;
+ var field = PngKeywords.FieldFor (keyword);
+ if (field != ImageStores.None)
+ return tag.Changed (field);
+ return PngKeywords.IsMirror (keyword, tag);
+ }
+
+ // A changed field is also changed in the XMP packet and the Exif profile that copy it, so that no reader shows
+ // the old value from there. A chunk with a bad CRC is not read by PNG decoders and is copied as it is.
+ static bool TryMirrorChunk (ReadOnlySpan whole, ImageTag tag, ref int budget, out byte[]? edited, out string? error)
+ {
+ edited = null;
+ error = null;
+ var type = whole.Slice (4, 4);
+ if (!PngChunks.CrcMatches (whole))
+ return true;
+ var payload = whole.Slice (8, whole.Length - 12);
+ if (type.SequenceEqual ("eXIf"u8)) {
+ var carrier = new ExifCarrier ("eXIf", exif => PngChunks.Chunk ("eXIf"u8, exif));
+ return carrier.TryEdit (payload, tag, out edited, out error);
+ }
+ if (!PngChunks.IsTextChunk (type) || !PngText.TryKeyword (payload, out var keyword, out var rest))
+ return true;
+ if (keyword is not (XmpKeyword or RawXmpKeyword or RawExifKeyword or RawApp1Keyword))
+ return true;
+ // Text no reader can decode (not zlib, or a broken international header) holds no copy: it is kept. Text that
+ // would pass the inflation budget may hold one, and cannot be checked.
+ if (!PngText.TryTextBody (type, payload.Slice (rest), ref budget, out var body, out var header, out var overBudget)) {
+ if (!overBudget)
+ return true;
+ error = $"The PNG {keyword} chunk does not fit in the {PngText.MaxInflatedText / (1024 * 1024)} MiB that all compressed text in the file shares, so its copy of a changed field cannot be updated.";
+ return false;
+ }
+
+ var text = new TextChunk (type.ToArray (), keyword, header);
+ if (keyword != XmpKeyword)
+ return TryMirrorRawProfile (text, body, tag, out edited, out error);
+ if (!TryMirrorXmp (Encoding.UTF8.GetString (body), tag, out var packet, out error))
+ return false;
+ edited = packet is null ? null : text.Build (Encoding.UTF8.GetBytes (packet));
+ return true;
+ }
+
+ // A text chunk's type, keyword and the header between the keyword and the text, to rebuild it around new text.
+ sealed class TextChunk (byte[] type, string keyword, byte[] header)
+ {
+ public string Keyword { get; } = keyword;
+
+ public byte[] Build (byte[] text) => PngText.Rebuild (type, Keyword, header, text);
+ }
+
+ // The updated packet, or null when it did not change.
+ static bool TryMirrorXmp (string packet, ImageTag tag, out string? updated, out string? error)
+ {
+ updated = null;
+ if (!XmpMirror.TryUpdate (packet, tag, "PNG XMP packet", out var result, out error))
+ return false;
+ if (!ReferenceEquals (result, packet))
+ updated = result;
+ return true;
+ }
+
+ static bool TryMirrorRawProfile (TextChunk text, byte[] body, ImageTag tag, out byte[]? edited, out string? error)
+ {
+ edited = null;
+ error = null;
+ // A profile that is not hexadecimal is decoded by no reader (exiftool: "Unknown raw profile"): there is no copy
+ // in it to update, and it is kept as it is.
+ if (!RawProfile.TryDecode (Polyfills.Latin1.GetString (body), out var name, out var profile))
+ return true;
+
+ byte[] Encode (byte[] bytes) => text.Build (Polyfills.Latin1.GetBytes (RawProfile.Encode (name, bytes)));
+ if (text.Keyword != RawXmpKeyword) {
+ var carrier = new ExifCarrier (text.Keyword, Encode);
+ return carrier.TryEdit (profile, tag, out edited, out error);
+ }
+ if (!TryMirrorXmp (Encoding.UTF8.GetString (profile), tag, out var packet, out error))
+ return false;
+ edited = packet is null ? null : Encode (Encoding.UTF8.GetBytes (packet));
+ return true;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Png/PngText.cs b/src/TagLibSharp2/Image/Png/PngText.cs
new file mode 100644
index 00000000..e3c418f3
--- /dev/null
+++ b/src/TagLibSharp2/Image/Png/PngText.cs
@@ -0,0 +1,236 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.IO.Compression;
+using System.Text;
+using TagLibSharp2.Core;
+
+namespace TagLibSharp2.Image.Png;
+
+///
+/// The PNG text chunks (PNG 3rd ed. §11.3.3): tEXt (Latin-1), zTXt (zlib-compressed Latin-1) and iTXt (UTF-8,
+/// optionally compressed, with a language tag and a translated keyword). Inflation shares one budget per file.
+///
+static class PngText
+{
+ /// All the text a file's compressed chunks may inflate to, together.
+ internal const int MaxInflatedText = 1024 * 1024;
+
+ /// The keyword (1-79 Latin-1 characters, then a null) and where the rest of the payload starts.
+ public static bool TryKeyword (ReadOnlySpan payload, out string keyword, out int rest)
+ {
+ keyword = "";
+ rest = 0;
+ var end = 0;
+ while (end < payload.Length && payload[end] != 0)
+ end++;
+ if (end == 0 || end >= payload.Length || end > 79)
+ return false;
+ keyword = Polyfills.Latin1.GetString (payload.Slice (0, end));
+ rest = end + 1;
+ return true;
+ }
+
+ /// The text of a chunk after its keyword's null, decoded.
+ public static bool TryText (ReadOnlySpan type, ReadOnlySpan rest, ref int budget, out string? text)
+ {
+ text = null;
+ if (type.SequenceEqual ("tEXt"u8)) {
+ text = Polyfills.Latin1.GetString (rest);
+ return true;
+ }
+
+ if (type.SequenceEqual ("zTXt"u8)) {
+ if (rest.Length < 1 || rest[0] != 0 || !TryInflate (rest.Slice (1), ref budget, out var raw))
+ return false;
+ text = Polyfills.Latin1.GetString (raw);
+ return true;
+ }
+
+ if (!TryInternationalHeader (rest, out var compressed, out var i))
+ return false;
+ var body = rest.Slice (i);
+ if (compressed) {
+ if (!TryInflate (body, ref budget, out var raw))
+ return false;
+ body = raw;
+ }
+
+ text = Encoding.UTF8.GetString (body.ToArray ());
+ return true;
+ }
+
+ // The text after the keyword's null, inflated when compressed. header is what sits between the keyword's null
+ // and the text: the zTXt method byte, or the iTXt flag, method, language tag and translated keyword. overBudget
+ // is set when the text was not read because it would pass the inflation budget.
+ public static bool TryTextBody (ReadOnlySpan type, ReadOnlySpan rest, ref int budget, out byte[] body, out byte[] header, out bool overBudget)
+ {
+ body = [];
+ header = [];
+ overBudget = false;
+ if (type.SequenceEqual ("tEXt"u8)) {
+ body = rest.ToArray ();
+ return true;
+ }
+
+ if (type.SequenceEqual ("zTXt"u8)) {
+ if (rest.Length < 1 || rest[0] != 0 || !TryInflate (rest.Slice (1), ref budget, out body, out overBudget))
+ return false;
+ header = [0];
+ return true;
+ }
+
+ if (!TryInternationalHeader (rest, out var compressed, out var i))
+ return false;
+ header = rest.Slice (0, i).ToArray ();
+ if (compressed)
+ return TryInflate (rest.Slice (i), ref budget, out body, out overBudget);
+ body = rest.Slice (i).ToArray ();
+ return true;
+ }
+
+ // iTXt after the keyword: compression flag, method, language tag and null, translated keyword and null.
+ static bool TryInternationalHeader (ReadOnlySpan rest, out bool compressed, out int textAt)
+ {
+ compressed = false;
+ textAt = 2;
+ if (rest.Length < 2)
+ return false;
+ compressed = rest[0] == 1;
+ return SkipToNull (rest, ref textAt) && SkipToNull (rest, ref textAt);
+ }
+
+ static bool SkipToNull (ReadOnlySpan data, ref int i)
+ {
+ while (i < data.Length && data[i] != 0)
+ i++;
+ if (i >= data.Length)
+ return false;
+ i++;
+ return true;
+ }
+
+ /// Inflates a zlib stream (RFC 1950), taking its size from the shared budget.
+ public static bool TryInflate (ReadOnlySpan zlib, ref int budget, out byte[] raw) => TryInflate (zlib, ref budget, out raw, out _);
+
+ // overBudget: set when the data was not inflated because it would pass the budget.
+ public static bool TryInflate (ReadOnlySpan zlib, ref int budget, out byte[] raw, out bool overBudget)
+ {
+ raw = [];
+ overBudget = budget <= 0;
+ if (overBudget || zlib.Length < 6 || (zlib[0] & 0x0F) != 8)
+ return false;
+ var header = (zlib[1] & 0x20) == 0 ? 2 : 6;
+ if (zlib.Length < header + 4)
+ return false;
+ try {
+ using var input = new MemoryStream (zlib.Slice (header, zlib.Length - header - 4).ToArray ());
+ using var stream = new DeflateStream (input, CompressionMode.Decompress);
+ if (!TryReadAll (stream, budget, out raw)) {
+ overBudget = true;
+ return false;
+ }
+
+ budget -= raw.Length;
+ return true;
+ } catch (InvalidDataException) {
+ return false;
+ } catch (IOException) {
+ return false;
+ }
+ }
+
+ static bool TryReadAll (Stream stream, int budget, out byte[] raw)
+ {
+ raw = [];
+ using var output = new MemoryStream ();
+ var buffer = new byte[8192];
+ var total = 0;
+ while (true) {
+ var read = stream.Read (buffer, 0, buffer.Length);
+ if (read == 0)
+ break;
+ if ((long)total + read > budget)
+ return false;
+ total += read;
+ output.Write (buffer, 0, read);
+ }
+
+ raw = output.ToArray ();
+ return true;
+ }
+
+ /// Compresses as a zlib stream (RFC 1950) for zTXt or a compressed iTXt.
+ internal static byte[] Zlib (byte[] raw)
+ {
+ using var output = new MemoryStream ();
+ output.WriteByte (0x78);
+ output.WriteByte (0x9C);
+ using (var deflate = new DeflateStream (output, CompressionLevel.Optimal, leaveOpen: true))
+ deflate.Write (raw, 0, raw.Length);
+ uint a = 1, b = 0;
+ foreach (var value in raw) {
+ a = (a + value) % 65521;
+ b = (b + a) % 65521;
+ }
+
+ var adler = (b << 16) | a;
+ output.WriteByte ((byte)(adler >> 24));
+ output.WriteByte ((byte)(adler >> 16));
+ output.WriteByte ((byte)(adler >> 8));
+ output.WriteByte ((byte)adler);
+ return output.ToArray ();
+ }
+
+ /// Rebuilds a text chunk of the same type around new text. Compression and the iTXt language tags are kept.
+ public static byte[] Rebuild (ReadOnlySpan type, string keyword, byte[] header, byte[] text)
+ {
+ var key = Polyfills.Latin1.GetBytes (keyword);
+ var compressed = type.SequenceEqual ("zTXt"u8) || (type.SequenceEqual ("iTXt"u8) && header.Length > 0 && header[0] == 1);
+ var body = compressed ? Zlib (text) : text;
+ var payload = new byte[key.Length + 1 + header.Length + body.Length];
+ key.CopyTo (payload, 0);
+ header.CopyTo (payload, key.Length + 1);
+ body.CopyTo (payload, key.Length + 1 + header.Length);
+ return PngChunks.Chunk (type, payload);
+ }
+
+ /// A new text chunk: tEXt when the value is Latin-1, otherwise an uncompressed iTXt.
+ public static void Add (BinaryDataBuilder builder, string keyword, string value)
+ {
+ if (IsLatin1 (value))
+ PngChunks.Add (builder, "tEXt"u8, Latin1Text (keyword, value));
+ else
+ PngChunks.Add (builder, "iTXt"u8, InternationalText (keyword, value));
+ }
+
+ static byte[] Latin1Text (string keyword, string value)
+ {
+ var key = Polyfills.Latin1.GetBytes (keyword);
+ var text = Polyfills.Latin1.GetBytes (value);
+ var payload = new byte[key.Length + 1 + text.Length];
+ key.CopyTo (payload, 0);
+ text.CopyTo (payload, key.Length + 1);
+ return payload;
+ }
+
+ static byte[] InternationalText (string keyword, string value)
+ {
+ var key = Encoding.ASCII.GetBytes (keyword);
+ var text = Encoding.UTF8.GetBytes (value);
+ var payload = new byte[key.Length + 5 + text.Length];
+ key.CopyTo (payload, 0);
+ text.CopyTo (payload, key.Length + 5);
+ return payload;
+ }
+
+ static bool IsLatin1 (string value)
+ {
+ foreach (var c in value) {
+ if (c > 0xFF)
+ return false;
+ }
+
+ return true;
+ }
+}
diff --git a/src/TagLibSharp2/Image/Png/RawProfile.cs b/src/TagLibSharp2/Image/Png/RawProfile.cs
new file mode 100644
index 00000000..020d01a6
--- /dev/null
+++ b/src/TagLibSharp2/Image/Png/RawProfile.cs
@@ -0,0 +1,86 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Globalization;
+using System.Text;
+
+namespace TagLibSharp2.Image.Png;
+
+///
+/// An ImageMagick raw profile in a PNG text chunk ("Raw profile type exif" and the like): a line feed, the profile
+/// name, a line feed, the byte count, a line feed, then the bytes as hexadecimal pairs split across lines.
+///
+static class RawProfile
+{
+ internal static bool TryDecode (string text, out string name, out byte[] bytes)
+ {
+ name = "";
+ bytes = [];
+ var i = 0;
+ while (i < text.Length && text[i] == '\n')
+ i++;
+ var nameEnd = text.IndexOf ('\n', i);
+ if (nameEnd < 0)
+ return false;
+ name = text.Substring (i, nameEnd - i);
+ i = nameEnd + 1;
+ while (i < text.Length && text[i] == ' ')
+ i++;
+ var countEnd = text.IndexOf ('\n', i);
+ if (countEnd < 0 || !TryCount (text, i, countEnd, out var count))
+ return false;
+ bytes = new byte[count];
+ return TryHexBytes (text, countEnd + 1, bytes);
+ }
+
+ static bool TryCount (string text, int from, int end, out int count)
+ {
+#if NETSTANDARD2_0
+ if (!int.TryParse (text.Substring (from, end - from), NumberStyles.None, CultureInfo.InvariantCulture, out count))
+#else
+ if (!int.TryParse (text.AsSpan (from, end - from), NumberStyles.None, CultureInfo.InvariantCulture, out count))
+#endif
+ return false;
+ return count >= 0 && count <= (text.Length - end) / 2;
+ }
+
+ static bool TryHexBytes (string text, int i, byte[] bytes)
+ {
+ for (var n = 0; n < bytes.Length; n++) {
+ while (i < text.Length && text[i] is '\n' or '\r' or ' ')
+ i++;
+ if (i + 1 >= text.Length || !TryHex (text[i], out var high) || !TryHex (text[i + 1], out var low))
+ return false;
+ bytes[n] = (byte)((high << 4) | low);
+ i += 2;
+ }
+
+ return true;
+ }
+
+ internal static string Encode (string name, byte[] bytes)
+ {
+ const string Digits = "0123456789abcdef";
+ var builder = new StringBuilder ((bytes.Length * 2) + (bytes.Length / 36) + name.Length + 16);
+ builder.Append ('\n').Append (name).Append ('\n');
+ builder.Append (bytes.Length.ToString (CultureInfo.InvariantCulture).PadLeft (8)).Append ('\n');
+ for (var n = 0; n < bytes.Length; n++) {
+ builder.Append (Digits[bytes[n] >> 4]).Append (Digits[bytes[n] & 0x0F]);
+ if (n % 36 == 35 || n == bytes.Length - 1)
+ builder.Append ('\n');
+ }
+
+ return builder.ToString ();
+ }
+
+ static bool TryHex (char c, out int value)
+ {
+ value = c switch {
+ >= '0' and <= '9' => c - '0',
+ >= 'a' and <= 'f' => c - 'a' + 10,
+ >= 'A' and <= 'F' => c - 'A' + 10,
+ _ => -1
+ };
+ return value >= 0;
+ }
+}
diff --git a/src/TagLibSharp2/Image/StillImageFile.cs b/src/TagLibSharp2/Image/StillImageFile.cs
new file mode 100644
index 00000000..e76abc41
--- /dev/null
+++ b/src/TagLibSharp2/Image/StillImageFile.cs
@@ -0,0 +1,402 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Diagnostics.CodeAnalysis;
+using TagLibSharp2.Core;
+using TagLibSharp2.Image.Tiff;
+
+namespace TagLibSharp2.Image;
+
+///
+/// A still image: JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, DNG, or SVG. Open one with ,
+/// , ,
+/// or .
+///
+///
+/// PNG text keywords, the GIF comment, and the JPEG COM marker can be edited
+/// through . copies every other byte,
+/// including the pixels. A path save copies those pixels in 64 KB pieces.
+/// BMP, PCX, Netpbm, TIFF, DNG, and SVG have no text
+/// block here yet, so is null and is
+/// the file that was read.
+///
+public sealed class StillImageFile : IMediaFile
+{
+ readonly byte[] _data;
+ readonly ImageTag? _tag;
+ IFileSystem? _fileSystem;
+
+ internal StillImageFile (byte[] data, MediaFormat format, ImageProperties? properties, ImageTag? tag)
+ {
+ _data = data;
+ _tag = tag;
+ Format = format;
+ ImageProperties = properties is { IsValid: true } ? properties : null;
+ }
+
+ /// Returns true when the data starts with the signature of a still-image format read here.
+ /// The start of the file.
+ /// Reads at most the first 64 KiB of markup for SVG and the IFD chain for TIFF; nothing is copied.
+ public static bool IsValidFormat (ReadOnlySpan data) => ImageHeader.TryDetect (data, out _);
+
+ /// Reads a still image from its bytes. The bytes are copied once.
+ /// The whole file.
+ /// The parsed file, or a failure naming why it could not be read.
+ /// A TIFF without the DNG version tag reads as TIFF; also treats a .dng name as DNG.
+ public static StillImageFileReadResult Read (ReadOnlySpan data) => Open (data.ToArray (), null);
+
+ /// Reads a still image from its bytes without an error string.
+ /// The whole file.
+ /// The parsed file when the read succeeds.
+ /// True when the data is a still image read here.
+ public static bool TryRead (ReadOnlySpan data, out StillImageFile? file)
+ {
+ var result = Read (data);
+ file = result.File;
+ return result.IsSuccess;
+ }
+
+ /// Reads a still image from disk. The file is read into memory once.
+ /// The file path.
+ /// Optional file system abstraction.
+ /// The parsed file, or a failure.
+ public static StillImageFileReadResult ReadFromFile (string path, IFileSystem? fileSystem = null)
+ {
+ var fs = fileSystem ?? DefaultFileSystem.Instance;
+ if (OpenFailure (path, fs) is { } missing)
+ return missing;
+
+ try {
+ byte[] bytes;
+ using (var stream = fs.OpenRead (path))
+ bytes = StreamBytes.ReadToEnd (stream);
+ return Remember (Open (bytes, path), path, fileSystem);
+ } catch (IOException ex) {
+ return StillImageFileReadResult.Failure ($"Failed to read file: {ex.Message}");
+ } catch (UnauthorizedAccessException ex) {
+ return StillImageFileReadResult.Failure ($"Access denied: {ex.Message}");
+ }
+ }
+
+ /// Reads a still image from disk asynchronously. The file is read into memory once.
+ /// The file path.
+ /// Optional file system abstraction.
+ /// Cancellation token.
+ /// The parsed file, or a failure.
+ public static async Task ReadFromFileAsync (
+ string path,
+ IFileSystem? fileSystem = null,
+ CancellationToken cancellationToken = default)
+ {
+ var fs = fileSystem ?? DefaultFileSystem.Instance;
+ if (OpenFailure (path, fs) is { } missing)
+ return missing;
+
+ try {
+ byte[] bytes;
+ using (var stream = fs.OpenRead (path))
+ bytes = await StreamBytes.ReadToEndAsync (stream, cancellationToken).ConfigureAwait (false);
+ return Remember (Open (bytes, path), path, fileSystem);
+ } catch (IOException ex) {
+ return StillImageFileReadResult.Failure ($"Failed to read file: {ex.Message}");
+ } catch (UnauthorizedAccessException ex) {
+ return StillImageFileReadResult.Failure ($"Access denied: {ex.Message}");
+ } catch (OperationCanceledException) {
+ return StillImageFileReadResult.Failure ("Operation was cancelled");
+ }
+ }
+
+ static StillImageFileReadResult? OpenFailure (string path, IFileSystem fileSystem)
+ {
+#if NETSTANDARD2_0 || NETSTANDARD2_1
+ if (path is null)
+ throw new ArgumentNullException (nameof (path));
+#else
+ ArgumentNullException.ThrowIfNull (path);
+#endif
+ return fileSystem.FileExists (path) ? null : StillImageFileReadResult.Failure ($"File not found: {path}");
+ }
+
+ static StillImageFileReadResult Remember (StillImageFileReadResult result, string path, IFileSystem? fileSystem)
+ {
+ result.File?.SetSource (path, fileSystem);
+ return result;
+ }
+
+ static StillImageFileReadResult Open (byte[] data, string? path)
+ {
+ if (!ImageHeader.TryDetect (data, out var format))
+ return StillImageFileReadResult.Failure ("Not a still image: no JPEG, PNG, GIF, BMP, PCX, Netpbm, TIFF, or SVG signature");
+ if (format == MediaFormat.Tiff && HasDngName (path))
+ format = MediaFormat.Dng;
+ return Open (data, format);
+ }
+
+ internal static bool HasDngName (string? path) =>
+ !string.IsNullOrEmpty (path) && Path.GetExtension (path).Equals (".dng", StringComparison.OrdinalIgnoreCase);
+
+ /// Opens as . The array is kept, not copied.
+ internal static StillImageFileReadResult Open (byte[] data, MediaFormat format)
+ {
+ if (!ImageHeader.TryRead (data, format, out var properties)) {
+ var cut = format is MediaFormat.Tiff or MediaFormat.Dng ? TiffSize.Ifd0NextCutShort (data) : null;
+ return StillImageFileReadResult.Failure (cut ?? $"Not a {format} image");
+ }
+ var tag = ImageRewrite.CreateTag (data, format);
+ return StillImageFileReadResult.Success (new StillImageFile (data, format, properties, tag));
+ }
+
+ ///
+ public Tag? Tag => _tag;
+
+ ///
+ public IMediaProperties? AudioProperties => null;
+
+ ///
+ public VideoProperties? VideoProperties => null;
+
+ ///
+ public ImageProperties? ImageProperties { get; }
+
+ ///
+ public MediaTypes MediaTypes => MediaTypes.Image;
+
+ ///
+ public string? SourcePath { get; private set; }
+
+ ///
+ public MediaFormat Format { get; }
+
+ ///
+ /// The file bytes after any text edit. Pixel data is not rewritten.
+ /// A container that cannot be updated safely is returned unchanged.
+ /// fails instead of writing that unchanged file, with the reason.
+ ///
+ public ReadOnlyMemory Render ()
+ {
+ if (!TryOutput (out var plan, out _))
+ return _data;
+ return plan.MaterializeShared (_data);
+ }
+
+ /// Writes the edited file to .
+ /// Fails, and does not write, when a text edit cannot be spliced into the container.
+ public FileWriteResult SaveToFile (string path, IFileSystem? fileSystem = null)
+ {
+#if NETSTANDARD2_0 || NETSTANDARD2_1
+ if (path is null)
+ throw new ArgumentNullException (nameof (path));
+#else
+ ArgumentNullException.ThrowIfNull (path);
+#endif
+ var fs = fileSystem ?? _fileSystem ?? DefaultFileSystem.Instance;
+ if (SpliceFormat && !string.IsNullOrEmpty (SourcePath))
+ return WriteSpliceSource (path, fs, default);
+ if (!TryOutput (out var plan, out var error))
+ return FileWriteResult.Failure (error);
+ return WritePlan (path, fs, plan);
+ }
+
+ /// Writes back to .
+ public FileWriteResult SaveToFile (IFileSystem? fileSystem = null)
+ {
+ if (string.IsNullOrEmpty (SourcePath))
+ return FileWriteResult.Failure ("No source path available. Use SaveToFile(path) instead.");
+ return SaveToFile (SourcePath!, fileSystem);
+ }
+
+ /// Writes to .
+ public Task SaveToFileAsync (
+ string path,
+ IFileSystem? fileSystem = null,
+ CancellationToken cancellationToken = default)
+ {
+#if NETSTANDARD2_0 || NETSTANDARD2_1
+ if (path is null)
+ throw new ArgumentNullException (nameof (path));
+#else
+ ArgumentNullException.ThrowIfNull (path);
+#endif
+ var fs = fileSystem ?? _fileSystem ?? DefaultFileSystem.Instance;
+ if (SpliceFormat && !string.IsNullOrEmpty (SourcePath))
+ return Task.FromResult (WriteSpliceSource (path, fs, cancellationToken));
+ if (!TryOutput (out var plan, out var error))
+ return Task.FromResult (FileWriteResult.Failure (error));
+ return Task.FromResult (WritePlan (path, fs, plan, cancellationToken));
+ }
+
+ bool SpliceFormat => Format is MediaFormat.Jpeg or MediaFormat.Png or MediaFormat.Gif;
+
+ // The source is opened before the plan. A splice failure disposes it and beats a cancelled token.
+ FileWriteResult WriteSpliceSource (string path, IFileSystem fileSystem, CancellationToken cancellationToken)
+ {
+ OpenedFile? source = null;
+ try {
+ if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var openError))
+ return openError;
+ if (!TryOutput (out var plan, out var error))
+ return FileWriteResult.Failure (error);
+
+ var opened = source!;
+ source = null;
+ return CopyOpened (path, opened, plan, cancellationToken);
+ } finally {
+ source?.Dispose ();
+ }
+ }
+
+ // Every format this file opens has a plan: a text rewriter, or the original bytes as one range.
+ bool TryOutput ([NotNullWhen (true)] out ImagePlan? plan, [NotNullWhen (false)] out string? error) =>
+ ImageRewrite.TryPlan (_data, Format, _tag, out plan, out error);
+
+ FileWriteResult WritePlan (
+ string path,
+ IFileSystem fileSystem,
+ ImagePlan plan,
+ CancellationToken cancellationToken = default)
+ {
+ if (string.IsNullOrEmpty (SourcePath))
+ return WriteHeld (path, fileSystem, plan, cancellationToken);
+ return WriteSource (path, fileSystem, plan, cancellationToken);
+ }
+
+ // Ranges stay in _data. The source file is not opened.
+ FileWriteResult WriteHeld (
+ string path,
+ IFileSystem fileSystem,
+ ImagePlan plan,
+ CancellationToken cancellationToken = default)
+ {
+ if (cancellationToken.IsCancellationRequested)
+ return FileWriteResult.Failure ("Operation was cancelled");
+
+ var chunk = StreamCopy.Rent ();
+ try {
+ return AtomicFileWriter.WriteStream (
+ path,
+ fileSystem,
+ output => plan.Write (null, _data, output, chunk, cancellationToken));
+ } finally {
+ StreamCopy.Return (chunk);
+ }
+ }
+
+ // Ranges are read back from the file that was opened, in the same order as Render.
+ FileWriteResult WriteSource (
+ string path,
+ IFileSystem? fileSystem,
+ ImagePlan plan,
+ CancellationToken cancellationToken = default)
+ {
+ OpenedFile? source = null;
+ try {
+ if (!PathSave.TryOpen (SourcePath!, fileSystem, out source, out var error))
+ return error;
+
+ var opened = source!;
+ source = null;
+ return CopyOpened (path, opened, plan, cancellationToken);
+ } finally {
+ source?.Dispose ();
+ }
+ }
+
+ // Caller has transferred ownership of source. This disposes it on every path.
+ static FileWriteResult CopyOpened (
+ string path,
+ OpenedFile source,
+ ImagePlan plan,
+ CancellationToken cancellationToken)
+ {
+ byte[]? chunk = null;
+ try {
+ if (source.Length < plan.SourceEnd)
+ return FileWriteResult.Failure ("The source ended before the requested bytes were copied");
+ if (cancellationToken.IsCancellationRequested)
+ return FileWriteResult.Failure ("Failed to re-read source file: Operation was cancelled");
+
+ chunk = StreamCopy.Rent ();
+ var copyBuffer = chunk;
+ return PathSave.Replace (path, source, output => {
+ plan.Write (source.Stream, default, output, copyBuffer, cancellationToken);
+ });
+ } finally {
+ source.Dispose ();
+ if (chunk is not null)
+ StreamCopy.Return (chunk);
+ }
+ }
+
+ /// Writes back to .
+ public Task SaveToFileAsync (
+ IFileSystem? fileSystem = null,
+ CancellationToken cancellationToken = default)
+ {
+ if (string.IsNullOrEmpty (SourcePath))
+ return Task.FromResult (FileWriteResult.Failure ("No source path available. Use SaveToFile(path) instead."));
+ return SaveToFileAsync (SourcePath!, fileSystem, cancellationToken);
+ }
+
+ ///
+ public void Dispose ()
+ {
+ }
+
+ internal void SetSource (string path, IFileSystem? fileSystem)
+ {
+ SourcePath = path;
+ _fileSystem = fileSystem;
+ }
+}
+
+///
+/// The result of reading a still image.
+///
+public readonly struct StillImageFileReadResult : IEquatable
+{
+ StillImageFileReadResult (StillImageFile? file, string? error)
+ {
+ File = file;
+ Error = error;
+ }
+
+ /// Gets the parsed file, or null when the read failed.
+ public StillImageFile? File { get; }
+
+ /// Gets the error message when the read failed.
+ public string? Error { get; }
+
+ /// Gets whether the read succeeded.
+ public bool IsSuccess => File is not null && Error is null;
+
+ /// Creates a successful result.
+ /// The parsed file.
+ /// The result.
+ public static StillImageFileReadResult Success (StillImageFile file) => new (file, null);
+
+ /// Creates a failed result.
+ /// The error message.
+ /// The result.
+ public static StillImageFileReadResult Failure (string error) => new (null, error);
+
+ ///
+ public bool Equals (StillImageFileReadResult other) => ReferenceEquals (File, other.File) && Error == other.Error;
+
+ ///
+ public override bool Equals (object? obj) => obj is StillImageFileReadResult other && Equals (other);
+
+ ///
+ public override int GetHashCode () => HashCode.Combine (File, Error);
+
+ /// Determines whether two results are equal.
+ /// The first result.
+ /// The second result.
+ /// True when both results hold the same file and error.
+ public static bool operator == (StillImageFileReadResult left, StillImageFileReadResult right) => left.Equals (right);
+
+ /// Determines whether two results differ.
+ /// The first result.
+ /// The second result.
+ /// True when the results differ.
+ public static bool operator != (StillImageFileReadResult left, StillImageFileReadResult right) => !left.Equals (right);
+}
diff --git a/src/TagLibSharp2/Image/Svg/SvgSize.cs b/src/TagLibSharp2/Image/Svg/SvgSize.cs
new file mode 100644
index 00000000..6ba55283
--- /dev/null
+++ b/src/TagLibSharp2/Image/Svg/SvgSize.cs
@@ -0,0 +1,353 @@
+// Copyright (c) 2025-2026 Stephen Shaw and contributors
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Globalization;
+using System.Text;
+using TagLibSharp2.Core;
+
+namespace TagLibSharp2.Image.Svg;
+
+///
+/// The width and height of an SVG: the root element's width and height attributes in absolute units, or its
+/// viewBox (SVG 1.1 §7.2, §7.7). Only the root start tag is decoded, never the document.
+///
+static class SvgSize
+{
+ // Reads only until the first code unit that cannot start a prolog, so an audio buffer stops at byte 0.
+ public static bool IsSvg (ReadOnlySpan data) => TrySvgRoot (new Markup (data), out _);
+
+ public static bool TryRead (ReadOnlySpan data, out ImageProperties? properties)
+ {
+ properties = null;
+ var markup = new Markup (data);
+ if (!TrySvgRoot (markup, out var start))
+ return false;
+
+ // Only the root start tag is decoded, never the document.
+ var end = TagEnd (markup, start);
+ var tag = markup.Decode (start, end);
+ if (TrySvgLength (tag, "width", out var width) && TrySvgLength (tag, "height", out var height))
+ properties = new ImageProperties (width, height, 0, "SVG");
+ else if (TryViewBox (tag, out width, out height))
+ properties = new ImageProperties (width, height, 0, "SVG");
+
+ return true;
+ }
+
+ // XML 1.0 §2.8 prolog: an XML declaration, then comments, processing instructions, white space and one
+ // doctype, then the root element. The scan reads code units in place (UTF-8, or UTF-16 after a BOM) and
+ // compares ASCII only, so nothing is decoded or copied.
+ static bool TrySvgRoot (Markup text, out int start)
+ {
+ start = 0;
+ var i = 0;
+ if (text.StartsAt (i, ""))
+ return false;
+ while (i < text.Length) {
+ while (i < text.Length && IsXmlSpace (text[i]))
+ i++;
+ if (i >= text.Length)
+ return false;
+ if (text.StartsAt (i, ""))
+ return false;
+ continue;
+ }
+
+ if (text.StartsAt (i, ""))
+ return false;
+ continue;
+ }
+
+ if (IsSvgRootAt (text, i)) {
+ start = i;
+ return true;
+ }
+
+ return false;
+ }
+
+ return false;
+ }
+
+ static bool IsSvgRootAt (Markup text, int i)
+ {
+ if (!text.StartsAt (i, "