Search code examples
imagepngimage-size

Can I safely append null bytes to a PNG image


I would like to append null bytes to a PNG file to match the previous size. I've successfully added 10 MB to a small image with no issue viewing the image. I am wondering if this is secure based on the definition of the PNG format or if I am just getting lucky from good error correction in software.

Update: I've removed why I want to do this.


Solution

  • Whether appending NULLs is safe or not depends upon the decoding application and library. If you want to be absolutely safe, insert a private chunk containing the NULLs. Note that this method will always add a minimum of 12 bytes to the file (4-byte length, 4-byte chunk name, zero or more NULL bytes, and a 4-byte CRC), of the form

    nnnnzpAD000000CRCN
    

    where

    nnnn = number of NULLs
    zpAD = chunk name
    0000000...  the NULLs
    CRCN = 4-byte CRC calculated over the chunk name and the NULLs
    

    Put this new "zpAD" chunk (or whatever you decide to call it) just ahead of the existing IEND chunk.