Search code examples
c#pngjpegexif

PNG or JPEG With Custom Text Chunk


I normally like to ask much more precise questions but in this one I haven't found any good place to get started.

Writing in C#, I am trying to add a large custom text chunk to an image and save this using either JPEG or PNG. I have found plenty of examples on using the Comments or UserComments tag and they work when the text is relatively short. In my case I need to add potentially large chunks of text, let's say up to 256K. I have found references to "custom chunks" but I can't find any good pointers on how to write and read them from C# without having to write a complete custom JPG or PNG encoder.


Solution

  • I'm not sure about JPG, but PNGs have a chunked format and as such it should be easy to add a custom chunk to a file that (well-written) existing decoders will ignore. This chunk can contain whatever data you want to put in it.

    You also don't need to write a full PNG decoder, simply look for you custom chunk and read/write it.

    Edit: JPEGs use segments (see page 2) to separate pieces of files. From my research, I didn't see any way to add a custom segment - but it is possible to use segment ids that are unused (that will be skipped by decoders) like JPG0, JPG13, DHP, EXP or something else. You can even split up the data across multiple blocks to increase the storage space (as pointed out by @BitBank).

    Hope this helps!