Repository navigation
Conversation
decriptor
force-pushed
the
feat/image-files
branch
3 times, most recently
from
November 23, 2026 01:33
6d37e1b to
cd7f171
Compare
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.
decriptor
force-pushed
the
feat/image-files
branch
from
November 24, 2026 03:07
fb1b043 to
76bd3b5
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
MediaFile.Read, andStillImageFile.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.Artistkeyword is read as the artist when there is noAuthor(PNG 3rd ed. predefinesAuthor, which wins).dc:title,dc:creator,dc:description,dc:rightsandexif:UserCommentkeep their own start and end tags (and any namespace they declare); only their content is replaced, as a singlex-defaultalternative or a one-itemrdf:Seq, or the property is removed for null. Carriers: PNGXML:com.adobe.xmp(iTXt/zTXt) and ImageMagick'sRaw profile type xmp, JPEG APP1 XMP, and the GIF XMP extension. The splice is one forward pass over the packet.ImageDescription,Artist,Copyright, the XP title/author/comment tags, and Exif-IFDUserCommentare removed from PNGeXIf, 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.Artistand ImageMagick'sexif:Artist/exif:ImageDescription/exif:Copyright/exif:UserCommentare dropped with the field.sample_xmpnullended.jpghas 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.Renderthen returns the original bytes andSaveToFiledoes not write.Clearremoves 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):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 (JUMBFjumbincl. C2PA,xml,uuid,json,Exif, unknown), maker segments such as SCALADO, and unknown APPn. Non-APP segments are kept.hdrgm:Version("1.0"),BaseRenditionIsHDR(Boolean),GainMapMin,GainMapMax,Gamma,OffsetSDR,OffsetHDR(a Real or three),HDRCapacityMin/Max(Real), and the primary'sContainer:DirectoryofContainer:Items with onlyItem: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 asrdf: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) andCamera: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) andHDRGainMap: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, soexiftool -validatewarns; 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-levelrdf:Descriptioncount; 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'sItem:Lengthis 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).assertion.dataHash.mismatch); keeping it would keep its assertions (identity, location), not provenance.iDOT; when a chunk betweeniDOTandIDATchanges,iDOTis dropped (its IDAT offset would be wrong; decoders then read IDAT in order).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/GIFNewCom):dc:titledc:creator, eXIfArtist, exiftoolArtistkeywordAuthor+ XMP Seq; Exif entry andArtistkeyword removedImageDescriptionCopyrightUserComment{Exif}UserCommentstaleUserComment,XPComment, XMPexif:UserComment{Exif}UserCommentstale (ImageIO never shows COM)exif:UserCommentxmp:CreateDate{Exif}DateTimeDigitizedTwin table
Save_KeepsTheBytesAfterTheImage,Png_AChunkAfterIend_IsNotReadOrEditedPng_WithoutIend_…,Gif_/Jpeg_UnspliceableSave_NamesTheReasonClear_DropsEveryMetadataCarrier_AndKeepsWhatTheDecoderNeeds(49 rows),Jpeg_Clear_DropsExifXmpIptc_AndUnknownApp1Jpeg_MultiPictureIndex_StillPointsAtEachImage,Jpeg_ClearOfAMultiPictureFile_WhoseIndexCannotBeFollowed_IsRefused,Jpeg_UnreadableMpfIndex_…ftyp,TONE,RTRF,LTRF,LCHK,SPEC,RESI) kept, every other box droppedClear_DropsEveryMetadataCarrier_…(JPEG XT box, JUMBF JSON/XML/C2PA, a JPEG XT box sharing En with a C2PA store, APP11 without JP)Png_AppleIdot_IsKeptOnlyWhileItStillPointsAtTheImageDataEdit_ChangesTheMirroredCopy_AndOnlyThatOne(70 rows),Read_ExiftoolArtistKeyword_IsTheArtistWhenThereIsNoAuthor,Edit_ImageMagickExifTextKeyword_…JpegAndGif_CommentEdit_ChangesTheExifAndXmpCopies(8 rows),Jpeg_CommentEdit_ThatCannotUpdateACopy_IsRefusedWithItsOwnReasonJpegAndGif_TitleIsNotStored_SoItsCopiesAreNotTouchedEdit_UpdatesTheTitleInEveryPacketShape(15 rows)Edit_XmpSplice_IsOnePassEdit_CompressedCopies_ShareOneInflationBudgetEdit_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)Edit_OfAFieldTheBlockDoesNotHold_KeepsTheBlockBytes(fill row),Jpeg_RewrittenExifSegment_KeepsTheFillBytesBeforeItEdit_OfAFieldTheBlockDoesNotHold_KeepsTheBlockBytes(10 rows)Edit_ThatCannotUpdateAMirror_IsRefusedWithItsOwnReasonJpeg_ZeroSofHeight_ReadsTheDnlAfterTheFirstScanDetectFormat_OfMarkup_…,Svg_DetectionCopiesNothing_…,Tiff_DetectionOfAReducedImageOrDng_AllocatesNoScratchStillImageFileEntryTests.*HDRGainMapVersionand noHDRGainMapHeadroom; 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 noneClear_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_IsLinearInTheEntriesClear_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)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)EveryIfdWalk_IsLinearInTheEntries(30 rows: steps at N and 4N, allocation at N, 2N and 4N, least of 3 runs)Clear_OfAVersion65536AppleGainMap_KeepsOnlyTheMakerNoteHeadroom(little-endian row),Clear_KeepsTheMakerNoteHeadroom_WhereverTheGainMapIsInTheIndex(2 rows)Clear_KeepsEveryEnumeratedItemValue(8 rows)Testing
dotnet build -c Release(4 TFMs): 0 warnings, 0 errors.dotnet format --verify-no-changesclean.dotnet packok. 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.TAGLIBSHARP2_TEST_AAC,_MPEGPS,_MP3,_WMAset to real files): 48 passed, 0 failed.NestingDepthTestsaddsjpeg-xmp-gainmap-clearandjpeg-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).Hostile.EveryTruncationandByteFlipsover 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.AssertLinearAllocationover 10 growing shapes.tools/fuzzover 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.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 reportsUltraHDRImage: Yes; ImageIO still finds the Apple gain map (agm.jpg,agm-dirty.jpg) and the ISO gain maps. exiftool-eefinds 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,m3and 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_boost3.4822, 4.4429, 2.9705 unchanged; the one sweep value libultrahdr refuses on input, it refuses after too), exiftool shows onlyHDRHeadroomandHDRGain, ffmpeg decodes cleanly. On a real iPhone 15 Pro Max maker note spliced intom1(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, fromm1-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 readsCamera:MotionPhoto1,MotionPhotoVersion1 andMotionPhotoPresentationTimestampUs500000, the video found by summing the item lengths is byte-identical and ffprobe reads it (h264 160x120, 10 frames), and the gain map's newItem:Lengthmatches the MPF size.Item:SemanticandItem:Mime, an item insiderdf:li>rdf:Description) saves without throwing, reads back, and keeps only typed gain-map values.Edit_ExifRemoval_IsLinearithmicInTheEntriesred.rdf:li>rdf:Descriptionitem, a slot with no item kept, a slot removed, the Semantic and Mime enumerations (any text, andMotionPhotoorvideo/mp4left out), AuxiliaryImageType, Boolean, Version, Integer, item Length and Long accepting any text, Long rejecting -1, NaN, Infinity, a secondContainer:Directory, a DTD parsed or ignored, the Camera properties, and a per-entryPointerInscan 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 Exifif (changed)) is unchanged.tools/compare/grid.cs --allplus 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-m3and 10 sweep values: maker-note headroom kept). Round 9 against 56ad4aa over 641 files (7 more fixtures): 2 rows change, the Clear cells ofdup21banddup30(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 0noopcells 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,
Clearremoves it); reading GIF XMP; SVG metadata elements; TIFF and DNG tag text; WebP. BMP, PCX, and Netpbm have no tag block.Type of Change
Checklist
dotnet test)Additional Notes
ImageTagis 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;Clearon a JPEG removes EXIF Orientation.