3

I want to insert a UTF-8 comment in a PNG. Context is in a modern browser : export -canvas- and add some metadata into PNG before user download, later import it and read metadata.

PNG specs for metadata, says about iTXt

I see a good answer here on SO about this, with all steps to achieve a tEXt chunk but without code.

I found a simple nodejs library node-png-metadata to manage PNG metadata.

With this resources, I succeeded some tricks like insert a chunk and read it, but it seem's it's not a valid iTXt chunk (same with tEXt chunk), because tools like pngchunks or pnginfo can't understand it.

See this working fiddle for playing import a PNG it will add metadata and display it ! Test with tEXt or iTXt chunk

Near line 21 some tests around creation of the chunk

var txt = {
  sample: '@à$'
};

var newchunk = metadata.createChunk("tEXt", "Comment"+String.fromCharCode(0x00)+"heremycommentl"); // works but not conform
var newchunk = metadata.createChunk("TEXt", "Comment"+String.fromCharCode(0x00)+"heremycommentl"); // result invalid png
var newchunk = metadata.createChunk("iTXt", "Source"+String.fromCharCode(0x00)+"00fr"+String.fromCharCode(0x00)+"Source"+String.fromCharCode(0x00)+""+JSON.stringify(txt));// works but not conform

Beside Resulting PNG is corrupted if chunk type name first char is upper case ? TEXt

If some of you have understanding to share, you're welcome

brouillon
  • 31
  • 2

1 Answers1

1

Chunk names are case-sensitive, tEXt is the name of the chunk, TEXt is not. And since the first letter is uppercase, making the chunk critical, no PNG tools can understand the image since there is now an unknown critical chunk.

The iTXt one is broken because the compression flag and method are stored directly, not as the ASCII representation of the numbers. Changing it to:

metadata.createChunk("iTXt", "Source"+String.fromCharCode(0x00)+String.fromCharCode(0x00)+String.fromCharCode(0x00)+"fr"+String.fromCharCode(0x00)+"Source"+String.fromCharCode(0x00)+""+JSON.stringify(txt));

makes it work.

metadata.createChunk("tEXt", "Comment"+String.fromCharCode(0x00)+"heremycommentl") doesn't cause any issues with pnginfo, perhaps you confused the error there with the iTXt one?

smitop
  • 4,770
  • 2
  • 20
  • 53