简体   繁体   中英

How can I append a tExt chunk into a canvas data array and save it as a png file in javascript?

I have an image in a canvas. I would like to include some simple text meta data without the need to install extra libraries. Looking at the result of toDataURL, this seems possible by parsing the base64 array from toDataURL result and inserting the chunk with length, type, key: content, and crc bytes before the IDAT chunk. However, I have not been able to match the base64 array to the png structure described in https://www.w3.org/TR/PNG-Structure.html . For example, the first 8 bytes are supposed to be signature bytes with the decimals: 137 80 78 71 13 10 26 10. But the first ASCii characters in the toDataURL result (after the data:image/png; base64," prefix) is iVBORw0. How does that match the expected signature?

I am using javascript and the conversion is done on the client side.

Thanks!

Thanks to Kaiido's comment above, I successfully decoded the toDataURL array using the base64-binary.js code here: http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/ . This is a snippet of how to use it:

  pngLayer = layerToSave.canvas.toDataURL();
  var uintArray = Base64Binary.decode(pngLayer.replace(/data:image\/png;base64,/,''));
  console.log("signature:", uintArray.slice(0,8));
  console.log("chunk 1 length:", uintArray.slice(8,12));
  console.log("chunk 1 type:", uintArray.slice(12,18));

This c code was also helpful as a sample of how to work with the png structure: https://github.com/gbenison/png-text-embed/blob/master/png-text-append.c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM