Skip to content

Open still images and write their text - #153

Open
decriptor wants to merge 1 commit into
mainfrom
feat/image-files
Open

decriptor wants to merge 1 commit 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: IFD0 ImageDescription, Artist, Copyright, the XP title/author/comment tags, and Exif-IFD UserComment are removed from PNG eXIf, ImageMagick's raw EXIF, and JPEG APP1 Exif. 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 (IFD0, IFD1, Exif, GPS, Interop), another entry's value, or the data an offset/length pair names (the IFD1 thumbnail, strips, tiles). The check sorts the protected ranges once and binary-searches them, and each IFD table is walked once however many entries point at it, so it is linear-logarithmic in the entries. A pointer (IFD0, Exif, GPS, Interop, IFD1) whose table is not inside the data is skipped, as ImageIO and exiftool skip it; a block that is not classic TIFF, or IFD tables that overlap beyond the data, refuse the save (before any table is walked). 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 TIFF or whose IFD0 or Exif IFD lies outside it; 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 edit of a TIFF with several Exif, GPS or interoperability IFDs (PNG eXIf, raw EXIF, JPEG APP1) setter, null UserComment removed from IFD0 and every Exif IFD; each distinct table walked once (its interoperability pointers and removal list included); every GPS and interoperability IFD protected from zeroing; a doubled offset/length pair zeroes nothing; overlapping tables refused before any walk; an unreadable IFD0, Exif, GPS, Interop or IFD1 pointer skipped Edit_RemovesTheCommentFromEveryExifIfd (8 rows), Edit_IfdsThatOverlap_AreRefusedBeforeTheyAreWalked (Exif, GPS), Edit_ManyPointersToOneTable_IsLinearInTheEntries (PNG and JPEG x self, one, mix: steps and allocation at N and 4N), Edit_SkipsAPointerNoReaderFollows (6 rows)
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)
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 7872 passed, 57 skipped, 0 failed of 7929; 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.
  • 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. 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 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.

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.70092% with 377 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.42%. Comparing base (5069025) to head (76bd3b5).

Files with missing lines Patch % Lines
src/TagLibSharp2/Image/ImageMirrors.cs 88.09% 46 Missing and 34 partials ⚠️
src/TagLibSharp2/Image/ImageRewrite.cs 90.88% 43 Missing and 37 partials ⚠️
src/TagLibSharp2/Image/ImageHeader.cs 93.50% 20 Missing and 24 partials ⚠️
...ests/TagLibSharp2.Tests/Image/ImageGainMapTests.cs 93.85% 0 Missing and 42 partials ⚠️
tests/TagLibSharp2.Tests/Image/ImageMirrorTests.cs 94.03% 1 Missing and 34 partials ⚠️
src/TagLibSharp2/Image/ImageGainMap.cs 86.45% 15 Missing and 19 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 ⚠️
...TagLibSharp2.Tests/Image/ImageSaveContractTests.cs 96.86% 0 Missing and 7 partials ⚠️
tests/TagLibSharp2.Tests/Kit/DepthCases.cs 89.70% 3 Missing and 4 partials ⚠️
... and 6 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #153      +/-   ##
==========================================
+ Coverage   93.39%   93.42%   +0.02%     
==========================================
  Files         415      432      +17     
  Lines       88291    94261    +5970     
  Branches    10288    11486    +1198     
==========================================
+ Hits        82462    88060    +5598     
- Misses       3429     3572     +143     
- Partials     2400     2629     +229     

☔ 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.

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