0
votes

I would like to know if there is a way in Python to measure the memory consumption of a PNG image.

For my test I've to Images normal.png and evil.png. Let's say both images are 100kb in size.

normal.png consists of data represented by 1 byte per pixel.

evil.png consists of \x00 bytes and a PLTE. chunk - 3 bytes per Pixel.

For normal.png I could decompress the IDAT data chunk, measure the size and compare it with the original file size to get an approximate memory consumption.

But how to proceed with evil.png ?

1
You mean, like width*height*depth?Antti Haapala

1 Answers

2
votes

You can use Pillow library to identify the image and to get the number of pixels and the mode, which can be transformed into the bitdepth:

from PIL import Image

mode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32, 
               'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}

i = Image.open('warty-final-ubuntu.png')
h, w = i.size

n_pixels = h * w
bpp = mode_to_bpp[data.mode]
n_bytes = n_pixels * bpp / 8

Image.open does not load the whole data yet; the compressed image in question is 3367987 bytes, 4096000 pixels and uses 12288000 bytes of memory when uncompressed; however straceing the python script shows that Image.open read only 4096 bytes from the file in memory.