pythonsizepngchunks

get size of PNG from bytes


I am trying to extract the size of an PNG image from a datastream

Consider the starting data of the stream

137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 2 84 0 0 3 74 8 2 0 0 0 195 81 71 33 0 0 0 ...
^                        ^        ^           ^                           ^            ^

which contains the following information

The information about the size of the image are encoded in the 8 bytes of the data chunk:

I know that the image has a width of 596 px and a height of 842 px but I cannot figure out how to compute the actual size of the image.

PS the values are given in Python and the here the datastream in binary form b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x02T\x00\x00\x03J\x08\x02\x00\x00\x00\xc3QG!\x00\x00\x00\tpHY'


Solution

  • You can think of each byte as a base-256 digit of the respective dimension. So 0 * 256^3 + 0 * 256^2 + 2 * 256 + 84 = 596, and 0 * 256^3 + 0 * 256^2 + 3 * 256 + 74 = 842.

    The next two bytes are important as well, where 8 is the bit depth, and 2 is the color type. 8 means 8 bits per component, and 2 means three components per pixel: red, green, and blue.