Skip to content

Open still images and write their text - #153

Open
decriptor wants to merge 9 commits into
mainfrom
feat/image-files
Open

decriptor wants to merge 9 commits into
mainfrom
feat/image-files

Conversation

@decriptor

@decriptor decriptor commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Description

MediaFile.Read, and StillImageFile.Read / TryRead / ReadFromFile / ReadFromFileAsync / IsValidFormat, open JPEG, PNG, GIF, BMP, PCX, Netpbm (PBM, PGM, PPM, PNM), TIFF, DNG, and SVG and report width and height.

  • A DNG, and a TIFF whose first IFD is a reduced-resolution preview, report the full-resolution image (the first 32 SubIFDs of an IFD are followed; at most 4096 IFDs and 64 SubIFD levels are read).
  • A JPEG whose frame height is 0 takes it from the DNL segment that follows the first scan (ITU-T T.81 §B.2.5).
  • Stored text: PNG keywords (Title, Author, Description, Copyright, Creation Time, Comment), the GIF comment, the JPEG COM marker. exiftool's PNG Artist keyword is read as the artist when there is no Author (PNG 3rd ed. predefines Author, which wins).
  • A save 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.
  • When a field changes, its copies elsewhere in the file change too (rule 4):
    • XMP: dc:title, dc:creator, dc:description, dc:rights and exif:UserComment keep their own start and end tags (and any namespace they declare); only their content is replaced, as a single x-default alternative or a one-item rdf:Seq, or the property is removed for null. Carriers: PNG XML:com.adobe.xmp (iTXt/zTXt) and ImageMagick's Raw profile type xmp, JPEG APP1 XMP, and the GIF XMP extension. The splice is one forward pass over the packet.
    • Exif: the changed field's tags (ImageDescription, Artist, Copyright, the XP title/author/comment tags, UserComment) are removed from PNG eXIf, ImageMagick's raw EXIF, and JPEG APP1 Exif, from every table exiftool reads with its Exif tags: IFD0 and the IFDs chained after it (IFD1, IFD2, ...), and every Exif IFD (0x8769) and SubIFD (0x014A) any of them points at, however deep (measured: exiftool shows each of these copies, e.g. [IFD1] Artist, [SubIFD] UserComment, a nested Exif IFD's UserComment; ImageIO and TagLib# read a subset). GPS and interoperability tables, and the next IFD of an Exif IFD or SubIFD (exiftool does not follow it), are kept. Each table is walked once, within a bound of one entry per 12 bytes and one SubIFD offset per 4 bytes (past it the tables overlap, and the save is refused only if the block's bytes could hold an entry with one of the field's tags: the tag followed by a TIFF or BigTIFF field type). The entry table shrinks in place. A removed value is zeroed only where nothing else uses its bytes: not the TIFF header, an IFD table, another entry's value, the data an offset/length pair names (the IFD1 thumbnail, strips, tiles), or the count, entries and next offset of a table no reader reads (zeroing must not make such a table readable); with an offset/length pair given twice nothing is zeroed. A table is read when its entries fit in the data, whether or not its 4-byte next-IFD offset does (exiftool, ImageIO and TagLib# read such a table), and a pointer whose table's entries do not fit is skipped, as those readers skip it (exiftool: "Bad ... directory"). A save is refused, with its own message and nothing written, only when it would rewrite structure: a table being compacted that shares a byte with another table, or an unread table's count or a SubIFD offset array inside a table being compacted. Tables that overlap but are not rewritten, and edits with nothing to remove, save. A block that is not classic TIFF is refused only when its bytes, read in either byte order, could hold an entry with one of the field's tags (a reader that knows another form may read it); otherwise it cannot hold a copy and keeps every byte. A rewritten segment keeps the fill bytes (0xFF) before its marker.
    • Text keywords: exiftool's Artist and ImageMagick's exif:Artist/exif:ImageDescription/exif:Copyright/exif:UserComment are dropped with the field.
    • A JPEG or GIF stores only the comment, so a comment edit changes the comment's copies there; Title and the other fields are not stored and their copies are never touched.
    • An XMP packet followed by NULs or padding (ImageIO writes one NUL after JPEG XMP; TagLib#'s sample_xmpnullended.jpg has a line feed and a NUL) is edited and its tail kept (XMP Part 1 §7.3), and GIF XMP written as data sub-blocks (as ImageIO writes it) is edited as well as the raw form with its magic trailer. A copy that cannot be updated safely refuses the save with its own reason: XMP that is not well-formed or declares a DTD; a value XML 1.0 cannot hold; an Exif block that is not classic TIFF and could hold the field, or whose IFD tables would be rewritten where they share bytes with other IFD structure; a raw profile that is not hex; compressed copies past the shared inflation budget; a JPEG XMP packet that would outgrow its APP1 segment; JPEG extended XMP, or a GIF XMP block in neither the raw form with its magic trailer nor data sub-blocks, that holds a UserComment. A container that cannot be spliced (PNG without IEND, a truncated GIF block list or JPEG marker list, a multi-picture JPEG whose MPF index cannot be corrected) also refuses with its own reason. Render then returns the original bytes and SaveToFile does not write.
  • Inflated PNG text is capped at 1 MiB for the whole file, on read and on save (the save's copy updates share one budget).
  • Clear removes all tag metadata (rule 7) and keeps only what a decoder or colour management needs, or the file's structure (the exception now recorded in the guide's rule 7):
    • PNG: critical chunks; tRNS, gAMA, cHRM, sRGB, iCCP, cICP, mDCV, cLLI, sBIT, bKGD, hIST, pHYs, sPLT, acTL/fcTL/fdAT, oFFs, pCAL, sCAL, sTER. Dropped: every other ancillary chunk, including text, XMP, raw profiles, eXIf, zxIf, tIME, caBX (C2PA), dSIG, iDOT, and unknown ones.
    • JPEG: APP0 JFIF/JFXX, APP2 ICC_PROFILE, MPF and ISO 21496-1 (the gain map), APP14 Adobe, the gain-map XMP an HDR decoder needs (below), and the APP11 JPEG XT decoding boxes ftyp, TONE, RTRF, LTRF, LCHK, SPEC, RESI (named in Artusi et al., "JPEG XT: A Compression Standard for HDR and WCG Images", IEEE Signal Processing Magazine 2016, §III and Fig. 3, which also says legacy decoders skip every APP11 box; the full Annex B list of ISO/IEC 18477-3 is not public, so refinement and alpha boxes, unnamed there, are dropped). Dropped: Exif, the rest of XMP (both signatures), extended XMP, APP13, APP12, FPXR, every other APP11 box (JUMBF jumb incl. C2PA, xml , uuid, json, Exif, unknown), maker segments such as SCALADO, and unknown APPn. Non-APP segments are kept.
    • HDR gain maps, in every image: Clear keeps the properties an HDR decoder needs and writes them into a new packet; nothing of the original packet is copied. Ultra HDR v1.0 (https://developer.android.com/media/platform/hdr-image-format): hdrgm:Version ("1.0"), BaseRenditionIsHDR (Boolean), GainMapMin, GainMapMax, Gamma, OffsetSDR, OffsetHDR (a Real or three), HDRCapacityMin/Max (Real), and the primary's Container:Directory of Container:Items with only Item:Semantic (Primary, GainMap, MotionPhoto), Item:Mime (image/jpeg, image/heic, image/avif, video/mp4, video/quicktime), Item:Length, Item:Padding; another Semantic or Mime is dropped and the item keeps its place and length, an item may be written as rdf:li > rdf:Description > Container:Item, and a directory with an entry that holds no item is dropped whole. Motion Photo 1.0 (https://developer.android.com/media/platform/motion-photo-format): Camera:MotionPhoto, Camera:MotionPhotoVersion (integers) and Camera:MotionPhotoPresentationTimestampUs (a long, -1 allowed), so a cleared motion photo is still one. Apple (as ImageIO writes an HDRGainMap auxiliary image): apdi:AuxiliaryImageType (urn:com:apple:photo:2020:aux:hdrgainmap), apdi:NativeFormat, apdi:StoredFormat, HDRGainMap:HDRGainMapVersion (integers) and HDRGainMap:HDRGainMapHeadroom (a Real, written from version 131072, iPhone 15). A version-65536 Apple gain map (iPhone 12-14) has no headroom in its XMP: ImageIO and libultrahdr take it from the primary's Apple maker note, tags 33 and 48 (Apple, "Applying Apple HDR effect to your photos"). For such a file Clear writes a new 114-byte Exif in the primary: IFD0 -> Exif IFD -> MakerNote (Apple iOS\0\0\x01MM) with only tags 33 and 48, copied as stored, and nothing else: no Make, Model, DateTime, GPS, other Exif tag or other maker-note tag. The values kept are those ImageIO applies, measured with every level duplicated and broken; TIFF 6.0 does not say which of two entries wins, and where libultrahdr reads a file differently (it takes the first Exif IFD pointer and MakerNote, refuses out-of-range ones, and reads a count-2 value), Clear follows ImageIO. The first Exif segment counts, and its TIFF magic must be 42. At every level, IFD0's 0x8769 Exif IFD pointers, each Exif IFD's 0x927C MakerNote entries and the maker note's 0x0021/0x0030 entries, an occurrence ImageIO cannot use is skipped and a later usable one overrides an earlier one: a pointer is usable when LONG or IFD, count 1, with its table inside the data, and two Exif IFDs merge value by value; a MakerNote when UNDEFINED, more than 4 bytes and inside the data, and either Apple's with its exact header and a table that fits (otherwise skipped) or another maker's (which then wins with no values); a tag entry when SRATIONAL with every value inside the maker note, at any offset (header and table included). The headroom is kept only when both winning entries have count 1 (otherwise ImageIO renders no HDR image). The kept Exif is a minimal carrier for the two decode parameters, not a conformant Exif: it deliberately omits Exif's mandatory format tags (ExifVersion, ComponentsConfiguration, ColorSpace, pixel dimensions, YCbCrPositioning, resolution), consistent with Clear removing all other Exif, so exiftool -validate warns; ImageIO, libultrahdr, ffmpeg, exiftool and TagLib# all read it. Without the two values ImageIO renders the photo SDR and libultrahdr refuses the file as a gain-map image. Only properties of a top-level rdf:Description count; a value of another shape, or with markup inside, is dropped; the first occurrence wins. The packet is read in one forward pass that keeps only the element path, so nesting never recurses and the cost is linear. When Clear shrinks a gain-map image, the primary's Item:Length is rewritten for the items the MPF index lists (a motion-photo video after them keeps its length and place). Verified with libultrahdr v2.0.2 (decode identical before and after Clear and edits on Google's own Ultra HDR files) and ImageIO's HDR decode (identical pixels for the Ultra HDR, ISO and every Apple file, version 65536 included).
    • Multi-picture JPEG (MPF, CIPA DC-007): Clear cleans every image the first image's MP index lists with the same rules (a gain-map image keeps its ISO 21496-1 APP2 and ICC profile) and rewrites each MP entry's offset and size. If the MP index lies outside its APP2 segment, or an entry points outside the file, before the first image's scan, overlaps another image, or does not start with SOI, Clear is refused with its own reason ("The JPEG MPF index cannot be read, so the metadata of the file's other images cannot be cleared."), and an edit that would move the later images is refused too; no byte outside the segment is written. An edit changes only the first image (the later images hold no copy of a mapped field) and updates the later images' offsets and image 1's size.
    • GIF: graphic control and plain text extensions, NETSCAPE2.0/ANIMEXTS1.0 and ICCRGBG1012. Dropped: XMP, ImageMagick IPTC/8BIM, unknown application extensions and undefined labels.
    • A C2PA manifest is dropped because any edit makes it fail its hard binding (C2PA 2.1 §14.3.3, §15.2 assertion.dataHash.mismatch); keeping it would keep its assertions (identity, location), not provenance.
  • Structure kept right: after an edit or Clear, every MP entry's offset still points at its image's SOI and every size is that image's length (CIPA DC-007 §5.2.3.3). New PNG text goes before Apple's iDOT; when a chunk between iDOT and IDAT changes, iDOT is dropped (its IDAT offset would be wrong; decoders then read IDAT in order).
  • Detection copies nothing: SVG is found by scanning UTF-8 or UTF-16 code units in place (first 64 KiB); the TIFF walk keeps its scratch on the stack and sizes any heap scratch from the input.

Behaviour survey (field edit)

Writers: exiftool 13.55 (tEXt incl. Artist, iTXt XMP, eXIf; JPEG COM, Exif UserComment, XPComment, XMP; GIF XMP), ImageMagick 7.1.2 (eXIf, zTXt raw XMP, exif:* tEXt). Readers after the edit (AT/AA/AD/AC/ACm, or JPEG/GIF NewCom):

field file ImageIO before ImageIO now exiftool now TagLib# now we write spec
Title PNG with XMP dc:title XMP value AT PNG:Title AT, XMP-dc:Title AT AT tEXt + XMP content XMP Part 1 §8.2.2.4 (Lang Alt)
Artist PNG with XMP dc:creator, eXIf Artist, exiftool Artist keyword XMP / Exif value AA PNG:Author AA, XMP-dc:Creator AA, no Artist n/a (not mapped) tEXt Author + XMP Seq; Exif entry and Artist keyword removed XMP §8.2.2.4; CIPA DC-008 Table 4; PNG 3rd ed. §11.3.3.2
Description PNG with XMP / eXIf ImageDescription XMP / Exif value AD PNG:Description AD, XMP-dc:Description AD (comment) AD tEXt + XMP; Exif entry removed same
Copyright PNG with XMP / eXIf Copyright XMP / Exif value AC PNG:Copyright AC, XMP-dc:Rights AC AC tEXt + XMP; Exif entry removed same
Comment PNG with XMP / eXIf UserComment {Exif}UserComment stale ACm PNG:Comment ACm, XMP-exif:UserComment ACm - tEXt + XMP; Exif entries removed CIPA DC-008 §4.6.5
Comment JPEG with COM, Exif UserComment, XPComment, XMP exif:UserComment {Exif}UserComment stale (ImageIO never shows COM) NewCom File:Comment NewCom, XMP-exif:UserComment NewCom, no Exif copies NewCom COM + XMP; Exif entries removed JPEG COM (T.81 §B.2.4.5); CIPA DC-008 §4.6.5
Comment GIF with comment and XMP exif:UserComment - - File:Comment NewCom, XMP-exif:UserComment NewCom - comment + XMP (magic trailer kept) GIF89a §24; XMP Part 3 §1.1.2
Year (Creation Time) PNG with XMP xmp:CreateDate {Exif}DateTimeDigitized unchanged unchanged - tEXt only not a copy: free text vs Exif date format

Twin table

site how reached fixed / n.a. pinning test
Tail after PNG IEND / GIF trailer / JPEG EOI Render, SaveToFile(Async); edit, null, Clear fixed Save_KeepsTheBytesAfterTheImage, Png_AChunkAfterIend_IsNotReadOrEdited
Unspliceable PNG / GIF / JPEG SaveToFile(Async) own error each Png_WithoutIend_…, Gif_/Jpeg_UnspliceableSave_NamesTheReason
Clear allow-lists PNG / JPEG / GIF (incl. C2PA, unknown APPn, chunks, extensions) Tag.Clear fixed Clear_DropsEveryMetadataCarrier_AndKeepsWhatTheDecoderNeeds (49 rows), Jpeg_Clear_DropsExifXmpIptc_AndUnknownApp1
JPEG MPF index and later images comment edit, null, Clear offsets and sizes rewritten; Clear cleans image 2+ (kept: ISO 21496-1, ICC); an edit leaves image 2+ as is (n.a.: no copy of a mapped field there) Jpeg_MultiPictureIndex_StillPointsAtEachImage, Jpeg_ClearOfAMultiPictureFile_WhoseIndexCannotBeFollowed_IsRefused, Jpeg_UnreadableMpfIndex_…
APP11 boxes Clear the seven JPEG XT decoding boxes (ftyp, TONE, RTRF, LTRF, LCHK, SPEC, RESI) kept, every other box dropped Clear_DropsEveryMetadataCarrier_… (JPEG XT box, JUMBF JSON/XML/C2PA, a JPEG XT box sharing En with a C2PA store, APP11 without JP)
Apple iDOT PNG edit insert before; drop when shifted Png_AppleIdot_IsKeptOnlyWhileItStillPointsAtTheImageData
PNG XMP / Exif / keyword copies (6 carriers + exiftool Artist) × 5 fields × {value, null} setter fixed Edit_ChangesTheMirroredCopy_AndOnlyThatOne (70 rows), Read_ExiftoolArtistKeyword_IsTheArtistWhenThereIsNoAuthor, Edit_ImageMagickExifTextKeyword_…
JPEG and GIF comment copies (Exif, XMP, spaced XMP signature, GIF XMP) Comment setter / null fixed JpegAndGif_CommentEdit_ChangesTheExifAndXmpCopies (8 rows), Jpeg_CommentEdit_ThatCannotUpdateACopy_IsRefusedWithItsOwnReason
JPEG / GIF Title, Artist, Description, Copyright setter n.a.: not stored, assignment ignored, file unchanged JpegAndGif_TitleIsNotStored_SoItsCopiesAreNotTouched
XMP packet shapes (attribute, empty element, two Descriptions, CRLF + astral, default-namespace rdf, own namespace, rdf declared or rebound on the property, rdf:resource / parseType, end tag with white space, nested Description, BOM) setter, null fixed Edit_UpdatesTheTitleInEveryPacketShape (15 rows)
XMP splice cost setter, null one pass Edit_XmpSplice_IsOnePass
Inflation budget on save edit with compressed copies shared, own refusal Edit_CompressedCopies_ShareOneInflationBudget
Exif zeroing setter only unshared bytes; linear-logarithmic Edit_RemovedExifValue_NeverZeroesBytesItShares (shared value, into the table, into the header), Edit_RemovedExifValue_KeepsBytesTheThumbnailIfd1OrGpsUse (IFD1 value, thumbnail, GPS value), Edit_ExifRemoval_IsLinearithmicInTheEntries (op count, N = 1k-8k)
Fill bytes before a JPEG marker Comment setter kept, rewritten or not Edit_OfAFieldTheBlockDoesNotHold_KeepsTheBlockBytes (fill row), Jpeg_RewrittenExifSegment_KeepsTheFillBytesBeforeIt
Blocks that hold no copy of the field (iTXt, compressed iTXt, zTXt, raw XMP, eXIf, raw EXIF, JPEG XMP/Exif, GIF XMP) setter bytes kept Edit_OfAFieldTheBlockDoesNotHold_KeepsTheBlockBytes (10 rows)
Refusals SaveToFile and SaveToFileAsync own message each Edit_ThatCannotUpdateAMirror_IsRefusedWithItsOwnReason
JPEG zero height all entry points DNL after first scan Jpeg_ZeroSofHeight_ReadsTheDnlAfterTheFirstScan
SVG / TIFF detection DetectFormat, IsValidFormat, TryRead copy-free DetectFormat_OfMarkup_…, Svg_DetectionCopiesNothing_…, Tiff_DetectionOfAReducedImageOrDng_AllocatesNoScratch
StillImageFile entry points span, TryRead, path sync/async added StillImageFileEntryTests.*
Apple v1 maker-note headroom Clear of an MPF JPEG whose kept gain-map packet has HDRGainMapVersion and no HDRGainMapHeadroom; first Exif of the primary only; the gain map's own Exif, a second Exif, v2, Ultra HDR, no gain map, a packet that outgrows its segment keep none kept (2 tags only) Clear_OfAVersion65536AppleGainMap_KeepsOnlyTheMakerNoteHeadroom, Clear_OfAVersion65536AppleGainMap_WithoutAValidMakerNoteHeadroom_KeepsNoExif (23 rows, incl. TIFF magic 43 in both byte orders and a duplicated entry whose last has count 2), Clear_KeepsNoExif_UnlessAVersion65536AppleGainMapNeedsTheMakerNote (5 rows), Clear_MakerNoteHeadroomWalk_IsLinearInTheEntries
Which occurrence wins: IFD0 0x8769, Exif IFD 0x927C, maker-note 0x0021 and 0x0030 Clear ImageIO's rule at every level (skip unusable, last usable wins, IFDs merge, count 1 at the end) Clear_KeepsTheHeadroomImageIOApplies_WhicheverOccurrenceWins (107 rows: level x {valid only, bad then valid, valid then bad, valid then another valid, bad only} x 8-9 kinds of bad occurrence per level), Clear_ManyPointersToOneExifIfd_WalkItOnce, Clear_ExifIfdPointerWalk_IsLinearInTheEntries, Clear_OverlappingExifIfdsOrMakerNotes_AreBoundedByTheData (2 rows)
Comment (and every mirrored field) edit of a TIFF with several IFDs (PNG eXIf, raw EXIF, JPEG APP1) setter, null the field's tags removed from IFD0's chain (IFD1, IFD2, ...) and every Exif IFD and SubIFD any of them points at, however deep, each table walked once; GPS, interoperability and the next IFD of an Exif IFD or SubIFD kept and protected; unread tables' count, entries and next offset never zeroed; a doubled offset/length pair zeroes nothing; refused only when a table being compacted shares a byte with another table, or an unread count or SubIFD offset array lies inside one; overlapping tables that are not rewritten, and edits with nothing to remove, save; a table whose entries fit read even without its next-IFD offset; a pointer whose table's entries do not fit skipped Edit_RemovesTheCommentFromEveryExifIfd (8 rows), Edit_RemovesTheCopiesExiftoolReadsInNestedTables (13 rows), Edit_LeavesTablesExiftoolDoesNotReadAsTheyAre (2), Edit_NeverZeroesTheCountOfATableNoReaderReads (6), Edit_SavesWhenNoTableItRewritesOverlapsAnother (7), Edit_ExifIfdsThatShareBytes_AreRefused (3), Edit_TablesThatTouchAnEditedTableAtItsEdge_AreRefused (3), Edit_APointerIntoTheMiddleOfAnEditedTable_IsRefused (2), Edit_KeepsSubIfdOffsetArraysAsTheyAre (2), Edit_IfdsThatOverlap_AreRefusedBeforeTheyAreWalked (2), Edit_ReadsATableWhoseNextOffsetIsMissing (10), Edit_ManyPointersToOneTable_IsLinearInTheEntries (6), Edit_SkipsAPointerNoReaderFollows (6)
A table without its next-IFD offset on Clear and on read Clear, read Clear keeps the Apple headroom from such an IFD0 or Exif IFD (ImageIO renders it HDR); the TIFF reader reports its size Clear_KeepsTheHeadroom_WhenATableHasNoNextOffset (4 rows), Tiff_WhoseIfdHasNoNextOffset_ReportsItsSize (2 rows), Tiff_IfdChainEndingWithoutANextOffset_IsReadLinearly
Every IFD walk: read, Clear (with the maker-note headroom walk), Comment edit read, Clear, setter linear in the entries for each worst shape (many pointers to IFD0, many to one Exif IFD, many distinct Exif IFDs, mixed interoperability and GPS pointers) in PNG eXIf and JPEG APP1 EveryIfdWalk_IsLinearInTheEntries (30 rows: steps at N and 4N, allocation at N, 2N and 4N, least of 3 runs; its read rows open PNG and JPEG, which walk no IFD, while the TIFF/DNG IFD walk is pinned by Tiff_IfdChainEndingWithoutANextOffset_IsReadLinearly and the "tiff IFD chain" row of ReadAndRewrite_AllocateLinearly); the least-of-runs measure itself by AssertLinearAllocation_QuadraticWork_FailsWithSeveralRuns and AssertLinearAllocation_OneNoisyRun_FailsWithOneRun_AndPassesWithSeveral
Other first-match lookups in the TIFF code read n.a.: the still-image TIFF/DNG dimension reader already takes the last valid ImageWidth/ImageLength; IFD1 is a single chain (one next-IFD offset); IFD0 duplicates of a removed tag were already all removed existing
Little-endian Exif TIFF / gain map not the last MPF image Clear kept Clear_OfAVersion65536AppleGainMap_KeepsOnlyTheMakerNoteHeadroom (little-endian row), Clear_KeepsTheMakerNoteHeadroom_WhereverTheGainMapIsInTheIndex (2 rows)
Enumerated item values Clear each kept Clear_KeepsEveryEnumeratedItemValue (8 rows)

Testing

  • dotnet build -c Release (4 TFMs): 0 warnings, 0 errors. dotnet format --verify-no-changes clean. dotnet pack ok. No vulnerable packages.
  • dotnet test -c Release: net8.0 8018 passed, 57 skipped, 0 failed of 8075; net10.0 the same. Skips need local sample files.
  • Env-gated integration tests (TAGLIBSHARP2_TEST_AAC, _MPEGPS, _MP3, _WMA set to real files): 48 passed, 0 failed.
  • Depth: NestingDepthTests adds jpeg-xmp-gainmap-clear and jpeg-xmp-comment (XMP nested as deep as one APP1 segment holds, about 9,000 levels, saved with Clear and with a Comment edit in a child process on a 1 MiB stack); both pass (the Clear case overflowed at 48b74a0).
  • Kit: Hostile.EveryTruncation and ByteFlips over 15 samples (incl. a version-65536 Apple gain map with its maker note) through detection, every read entry point and edit/mirror-edit/Clear renders; Bounds.AssertLinearAllocation over 10 growing shapes. tools/fuzz over 181 real and generated files (incl. the reviewer's hostile gain-map packets and libultrahdr's Ultra HDR files): 135,650 cases, 0 throws, 0 slow.
  • Real decoders after Clear, a Comment edit, and Clear then a Comment edit: libultrahdr v2.0.2 (ultrahdr_app -m 1) decodes all 11 Ultra HDR files (9 written by libultrahdr, 2 built by hand to the format) and the 2 Core Image ISO gain-map files to the same pixels as before, and reports UltraHDRImage: Yes; ImageIO still finds the Apple gain map (agm.jpg, agm-dirty.jpg) and the ISO gain maps. exiftool -ee finds no personal field in any image after Clear. ImageIO's HDR decode (kCGImageSourceDecodeToHDR) gives identical pixels before and after on every Ultra HDR, ISO and Apple file. The version-65536 Apple files (m1, m2, m3 and 56 maker-note sweep values) keep their HDR rendition after Clear: ImageIO max abs diff 0 on all, libultrahdr's HDR decode is md5-identical to the input's (max_content_boost 3.4822, 4.4429, 2.9705 unchanged; the one sweep value libultrahdr refuses on input, it refuses after too), exiftool shows only HDRHeadroom and HDRGain, ffmpeg decodes cleanly. On a real iPhone 15 Pro Max maker note spliced into m1 (m1-real) and its variants with a duplicated 0x0021 or 0x0030, a duplicated entry whose last or first is RATIONAL or FLOAT, and two Exif segments, ImageIO's HDR decode after Clear is identical to the input's. Over 148 crafted files (the reviewer's 34 and 114 more covering each level x pattern x kind, from m1-real), ImageIO renders the cleared file exactly as the input wherever the input renders HDR (105, decode digest identical) and SDR wherever the input renders SDR or no HDR image (43). libultrahdr renders 85 of them the same before and after; the other 63 are files it reads differently from ImageIO (first pointer or MakerNote, out-of-range refusals, count-2 values, single tags, TIFF magic), where Clear follows ImageIO. The version-131072 Apple files keep their headroom: ImageIO peaks 3.47 and 1.49 and libultrahdr's decode are unchanged. On a motion photo built from a libultrahdr file plus a 5,400-byte H.264 MP4, after Clear exiftool reads Camera:MotionPhoto 1, MotionPhotoVersion 1 and MotionPhotoPresentationTimestampUs 500000, the video found by summing the item lengths is byte-identical and ffprobe reads it (h264 160x120, 10 frames), and the gain map's new Item:Length matches the MPF size.
  • Exif edit matrix (ImageExifMatrixTests):
    • Structures (20): IFD0, IFD1, IFD2; Exif IFDs from IFD0, nested and from IFD1; a SubIFD given inline and one given by an offset array (and the array itself); GPS, interop and a table no reader reads; the removed UserComment in each of six tables, the removed XPComment, and a kept value.
    • For every ordered pair, the second structure's first or last byte is placed on each part of the first: its count, its entries, its next offset or its value bytes. Further placements: same start, inside, covers, touching on either side, sharing the first or last byte. Disjoint is the base layout.
    • Both byte orders; JPEG APP1, PNG eXIf and the PNG raw EXIF profile: 21,054 inputs for each of Comment, Comment null, Artist, Title, Description, Copyright, a no-op save and Clear.
    • The oracle is a test-side TIFF reader (ExifReaderModel, not the library's code):
      • a save leaves every table, entry, value and SubIFD array a reader sees as it was, except the removed copies, and no unread table becomes readable;
      • a refusal needs a reason the reader confirms from the layout;
      • a field with no copy always saves with the Exif bytes unchanged.
    • 0 failures. Comment: 14,832 saves, 6,222 refusals (compacted table overlaps another 4,527; unread count in a compacted table 1,218; SubIFD array in one 459; entry bound 18). Title, Description, Copyright, no-op and Clear: 0 refusals.
    • At 5a33c2f the same test fails:
      • Comment: 621 tables made readable, 663 refused when safe, 17,652 copies left or entries changed;
      • Title, Description and Copyright: 640 refusals each with nothing to remove.
    • It also found a new neighbour at 1081d0c: 12 refusals with nothing to remove for each of Title, Description and Copyright. The entry bound refused before checking whether the field could be there at all; this is now fixed.
  • Mutation (Stryker.NET on the changed Exif-edit lines): 306 mutants; after the new tests 291 tested, 273 killed. Three guards the run showed could never change a result were removed. The remaining survivors are equivalent: the step counters for the scaling pins, empty-range comparisons (> vs >=, < vs <= where the range is empty either way), the clip of an unread table's entries to the data (they run past the end in every case that reaches it), and a re-walk bound of at most 3 per table. The tag scan added this round has 14 targeted reverts (each early return, the byte-order choice, the scan's start and end, each bound of the type range, the type check and its offset); all 14 turn a test red.
  • Every hostile gain-map packet from review (duplicates, nested personal data, typed nodes, rdf:about text, second RDF, prefix clash, 1,000 to 9,000-level nesting, a packet that would outgrow its segment, free text in Item:Semantic and Item:Mime, an item inside rdf:li > rdf:Description) saves without throwing, reads back, and keeps only typed gain-map values.
  • Op count: every per-entry collection of the Exif removal is a counted list (no search, no enumerator); the reviewer's quadratic dedup of the removed or protected ranges now turns Edit_ExifRemoval_IsLinearithmicInTheEntries red.
  • Guard reverts, each applied alone: round 6 adds 10 (O1, O2, typed values, first attribute wins, markup inside a value, top-level Description only, element-form item fields, motion-photo lengths, spaced signature on Clear, segment-size guard) and all 10 turn a test red. Round 7 adds 22: the headroom, the rdf:li > rdf:Description item, a slot with no item kept, a slot removed, the Semantic and Mime enumerations (any text, and MotionPhoto or video/mp4 left out), AuxiliaryImageType, Boolean, Version, Integer, item Length and Long accepting any text, Long rejecting -1, NaN, Infinity, a second Container:Directory, a DTD parsed or ignored, the Camera properties, and a per-entry PointerIn scan of the IFD table (now counted in the Exif step bound); all 22 turn a test red. Round 8 adds 20 for the maker-note headroom (IFD0 and Exif IFD tables in the data, MakerNote type, minimum size and bounds, header, entry table in the maker note, SRATIONAL, count 1, value offset after the table and inside the maker note, both tags required, first Exif only, the headroom/version condition both ways, the flag after the segment-size check, later images keep none, a per-entry rescan) and the two MIME enumeration reverts (22); all turn a test red. Round 9 drops the header-result check (a non-TIFF header leaves IFD0 at 0, which the IFD0 table check refuses, so it could not change an outcome) and adds 5 more: first occurrence wins, a wrong type refused instead of skipped, any TIFF magic, only the first or only the last later MPF image counting; all 24 maker-note reverts (and both MIME reverts) now turn a test red. Round 10 replaces the maker-note guards with 21 reverts of the occurrence rule (pointer type, IFD type, count and table; Exif IFD walked again; first IFD wins; both budgets; foreign maker note read as Apple's; MakerNote type, size, range, exact header, table fit; tag type, count 0, range and one byte past; first tag entry wins; a count-2 winner kept; quadratic walk) and 8 of the edit path (first Exif IFD only, first GPS IFD only, interop of the first Exif IFD only, a doubled pair still zeroing, overlap walked, Exif IFD that is IFD0 skipped, one Exif IFD walked twice, a zero pointer refused); with the 9 round-9 ones that still apply and the 2 MIME ones, all 40 turn a test red (3 needed a new test first: an Exif IFD walked again, the IFD budget, one Exif IFD compacted twice). Round 11 reworks the edit-path reverts and adds 5 (each pointer walks its Exif IFD again, other IFDs walked again, an unreadable Exif IFD or IFD0 refusing the save, the overlap refusal moved after the walk); all 44 turn a test red. Round 12 adds 7 (a table needing its next offset, the offset read or cleared past the data, the overlap by entry count, the pointer-into-a-table check off for Exif and for GPS/Interop/IFD1, the TIFF reader needing the offset); all 51 turn a test red. Round 13 replaces the edit-path reverts with 18 for the IFD walk and the scoped refusals (chain, nested Exif IFDs and SubIFDs not followed; an Exif IFD's next read as a main IFD; GPS/interop edited; IFD0-only tags; unread structure not protected; the conflict checked before the early return; any overlap refused; an unread pointer in any table refused; SubIFD arrays in a compacted table allowed; no entry or offset bound; arrays read again; nothing removed outside IFD0; the boundary reverts R9, R10, R12); with the Clear and read reverts kept, all 54 turn a test red. Earlier rounds' red reverts still hold; the one equivalent mutant (JPEG Exif if (changed)) is unchanged.
  • Before/after grid (tools/compare/grid.cs --all plus Comment-set and Comment-null columns, 634 files: TagLib# samples, TaglibSharpSamples and 31 gain-map fixtures) against d066eb3: 13 rows change, all Clear cells of version-65536 Apple files (m1-m3 and 10 sweep values: maker-note headroom kept). Round 9 against 56ad4aa over 641 files (7 more fixtures): 2 rows change, the Clear cells of dup21b and dup30 (the last entry is kept). Round 10 against 4f0874f over 666 files: 14 rows change, all Clear cells of the reviewer's round-10 crafted files (each now rendered by ImageIO as its input). Round 13 against 5a33c2f over 1,238 files (every crafted or real image from rounds 8-13, 635 distinct, plus both sample sets; every operation): only round-13 shapes change: nested, IFD1, IFD2 and SubIFD copies now removed, the zero-be shape keeps the unread table's count (no reader shows its hidden comment), and the overlap, GPS/IFD1 and interop-pointer shapes that rewrite nothing now save; 99 -> 37 SAVEFAIL cells. The reviewer's differential fuzz (seeds 1-3, 120,000 Comment edits; its reader updated to the measured graph: IFD0 chain, nested Exif IFDs and SubIFDs, truncated SubIFD arrays unread): 0 wrong saves (76bd3b5: 53,318; 5a33c2f: 18,812), 44,456 refusals, of which 4,148 were correct saves at 76bd3b5. Round 12 against 76bd3b5 over 1,160 files (every crafted or real image from rounds 8-12, 557 distinct, plus both sample sets; every operation): only the round-12 shapes change: the no-next-offset files now save with the copies removed (exiftool, ImageIO and TagLib# show no old UserComment or XPComment; Clear keeps HDR, ImageIO diff 0), the overlap files are refused, and two no-next-offset TIFFs open. The reviewer's oracle fuzz (8 seeds x 20,000 Comment edits) leaves 0 stale copies and 0 changed kept values, with 0 throws. Round 11 against c3ca631 over 1,055 files (TagLib# samples, TaglibSharpSamples and every crafted or real image from rounds 8-11, 452 distinct), with Description, Copyright and null columns for every field added (and 5 more of my own probe files run separately): 12 cells change (plus the probe files' F2 cells), all Comment saves of files with an Exif IFD pointer no reader follows that used to be refused (now saved, the real Exif IFD updated). The reviewer's 1,000-32,000-pointer eXIf files now take 12 steps per entry and 49-51 MB peak memory (were up to 1.02 billion steps and 1.09 GB). 0 Comment cells, 0 non-image rows and 0 noop cells change. The matrix commit against a9c06f9 over the same 1,238 files: 0 rows change. The tag-scan fix (610801f) against 1081d0c: 2 rows change, the Comment cells of magic00.jpg and magic2b.jpg (real camera Exif with the TIFF magic changed): they hold no UserComment or XPComment tag in either byte order and now save instead of being refused.

Motivation and Context

Part of #111. This does not finish the issue, and merging it should not close #111.

Still out of this PR: reading EXIF, IPTC, and XMP values (a PNG with only an XMP title reads Title null; null on it changes nothing, Clear removes it); reading GIF XMP; SVG metadata elements; TIFF and DNG tag text; WebP. BMP, PCX, and Netpbm have no tag block.

Type of Change

  • New feature (non-breaking change that adds functionality)
  • Bug fix (non-breaking change that fixes an issue)

Checklist

  • I have read the CONTRIBUTING guidelines
  • My code follows the project's code style
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass (dotnet test)
  • I have updated documentation as needed
  • My changes generate no new warnings

Additional Notes

ImageTag is a leaf format tag. Residual: no real Photoshop, Lightroom, GIMP, iPhone or Pixel (Ultra HDR) files, camera MPO, or signed C2PA files were tested (the Apple gain map is ImageIO-written, the Core Image gain map is real, the Ultra HDR files are Google's libultrahdr v2.0.2 output and one hand-built file, the rest are exiftool-, ImageMagick- or code-made); JPEG XT refinement and alpha boxes, which no public source names, are dropped on Clear; which maker-note 33/48 types real iPhones write is not checked on a real file (the Apple files are ImageIO-written, with SRATIONAL; ImageIO applies no other type); exiftool reads ImageIO's sub-block GIF XMP as raw bytes, the same before and after an edit; the PNG raw IPTC profile is left on an edit (ImageIO does not read it); a bad-CRC XMP chunk is copied as is; replacing an rdf:Alt drops the other languages (intended); Exif 3.0 ImageTitle is not treated as a copy of Title; Clear on a JPEG removes EXIF Orientation.

@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.94376% with 420 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.44%. Comparing base (5069025) to head (610801f).

Files with missing lines Patch % Lines
src/TagLibSharp2/Image/ImageRewrite.cs 90.88% 43 Missing and 37 partials ⚠️
src/TagLibSharp2/Image/ImageMirrors.cs 89.63% 44 Missing and 32 partials ⚠️
tests/TagLibSharp2.Tests/Image/ImageMirrorTests.cs 94.77% 1 Missing and 56 partials ⚠️
...ests/TagLibSharp2.Tests/Image/ImageGainMapTests.cs 93.95% 0 Missing and 43 partials ⚠️
src/TagLibSharp2/Image/ImageHeader.cs 94.07% 18 Missing and 22 partials ⚠️
src/TagLibSharp2/Image/ImageGainMap.cs 86.45% 15 Missing and 19 partials ⚠️
...s/TagLibSharp2.Tests/Image/ImageExifMatrixTests.cs 89.77% 13 Missing and 10 partials ⚠️
tests/TagLibSharp2.Tests/Image/ImageWriteTests.cs 96.10% 8 Missing and 12 partials ⚠️
src/TagLibSharp2/Image/StillImageFile.cs 90.72% 4 Missing and 5 partials ⚠️
tests/TagLibSharp2.Tests/Image/ImageBoundsTests.cs 95.12% 0 Missing and 8 partials ⚠️
... and 8 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #153      +/-   ##
==========================================
+ Coverage   93.39%   93.44%   +0.04%     
==========================================
  Files         415      434      +19     
  Lines       88291    95211    +6920     
  Branches    10288    11719    +1431     
==========================================
+ Hits        82462    88967    +6505     
- Misses       3429     3582     +153     
- Partials     2400     2662     +262     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@decriptor
decriptor force-pushed the feat/image-files branch 3 times, most recently from 6d37e1b to cd7f171 Compare November 23, 2026 01:33
MediaFile.Read and StillImageFile (Read, TryRead, ReadFromFile,
ReadFromFileAsync, IsValidFormat) open JPEG, PNG, GIF, BMP, PCX,
Netpbm, TIFF, DNG and SVG and report width and height. A DNG or a TIFF
whose first IFD is a preview reports the full-resolution image, and a
JPEG with frame height 0 takes it from the DNL after the first scan.

Text is read and written where each format stores it: PNG keywords
(Title, Author, Description, Copyright, Creation Time, Comment), the GIF
comment and the JPEG COM marker. A save copies every other byte,
including anything after IEND, the GIF trailer or EOI, and a no-op save
is byte-identical.

When a field changes, its copies elsewhere in the file change too:
- XMP dc:title, dc:creator, dc:description, dc:rights and
  exif:UserComment are edited in place in one forward pass.
- The matching Exif tags are removed from every Exif IFD. A value's
  bytes are zeroed only when nothing else uses them, and each IFD table
  is walked once.
- exiftool's and ImageMagick's text keyword copies are dropped.
A copy that cannot be updated safely refuses the save with its own
reason, and nothing is written.

Clear removes all tag metadata and keeps only what a decoder or colour
management needs (the exception is added to guide rule 7):
- PNG critical chunks plus the colour, transparency, physical and
  animation chunks.
- JPEG JFIF, ICC, MPF, ISO 21496-1 and Adobe segments, and the JPEG XT
  decoding boxes.
- GIF control, plain-text and loop extensions.
- The HDR gain-map properties of Ultra HDR, Motion Photo and Apple gain
  maps, written into a new packet.
- For a version-65536 Apple gain map, a 114-byte Exif holding only the
  maker-note headroom tags 33 and 48. They are chosen as ImageIO chooses
  them when entries repeat or are broken.
Every image of a multi-picture JPEG is cleaned, and its MP index and
Item:Length values are rewritten. C2PA manifests are dropped.

Inflated PNG text is capped at 1 MiB per file. Every walk is linear in
the bytes present, pinned by step-count and allocation tests.
Detection copies nothing.
… that share bytes

A table is read when its entries fit in the data, as exiftool, ImageIO and
TagLib# read it; a missing or cut next-IFD offset is taken as 0. The edit
removes the copies from such a table and protects one from zeroing, Clear
keeps the Apple headroom from it, and the TIFF reader reports its size. The
overlap refusal now compares byte ranges (one sort), and a pointer to an
unreadable table that lands inside an edited one is refused with its own
reason. The test oracle reads tables as the readers do.
…in the TIFF walk

A quadratic allocation still fails with three runs, and linear work with
one noisy run fails with one run and passes with three.
…ope refusals

The Comment and other edits now walk IFD0's chain of IFDs and every Exif IFD
and SubIFD any of them points at, each table once within the entry and
offset bounds, and remove the changed field's tags from each, as exiftool
shows a copy from any of them. Zeroing a removed value never touches the
count, entries or next offset of a table no reader reads. A save is refused
only when a table being compacted overlaps another table, or an unread
table's count or a SubIFD offset array lies inside one; an edit with
nothing to remove saves. Pinned against an exiftool-model test reader,
boundary rows, and scaling shapes for nested chains, SubIFDs and cycles.
…ndent reader

Adds a structure-by-relation matrix over IFD0, Exif, nested, IFD1,
SubIFD, GPS, interop, unread tables and the removed and kept values,
in both byte orders and every carrier. A test-side reader states what
a save must keep and when a refusal is justified. Per-finding tests now
assert the full reader-visible result, and new rows cover the data
edges, the entry bound and the refusal message. Three guards that the
mutation run showed could never change the result are removed.
A block that is not classic TIFF, or whose IFD tables overlap past the
entry bound, was refused even when it held no copy of the changed
field. It is now refused only when its bytes could hold an entry with
one of the field's tags (the tag followed by a TIFF or BigTIFF type, in
either byte order for a block that is not classic TIFF); otherwise
there is nothing to remove and the block keeps every byte. The Exif
matrix now places each structure's first or last byte on every part of
the others (count, entries, next offset, value), adds IFD2 and a SubIFD
given by an offset array, and compares the arrays' bytes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Read and write image metadata

1 participant