Search code examples
compressionpng

Maximum PNG size according to resolution


Is there a way to calculate the Maximum size that could take any image compressed with PNG ?

I need to know, that (for example) a PNG of a resolution of 350x350 (px), can't be larger than "X" KB. (and for a constant quality compression, like 90)

the "X" value is the one I'm looking for. Or in math expression

350px *  350px * (90q) < X KB

I'm not quite familiar with the PNG compression algorithm, but there is probably a max value for a specific resolution ?

P.S. : the PNG has no alpha is this case.


Solution

  • From the PNG format here:

    The maximum case happens when the data is incompressible
    (for example, if the image resolution is 1x1,
    or if the image is larger but contains random incompressible data).

    That would make the maximum size:

       8 // PNG signature bytes
    + 25 // IHDR chunk (Image Header)
    + 12 // IDAT chunk (assuming only one IDAT chunk)
    + height // in pixels
      * (
            1 // filter byte for each row
          + (
             width // in pixels
             * 3   // Red, blue, green color samples
             * 2   // 16 bits per color sample
            )
        )
    +  6 // zlib compression overhead
    +  2 // deflate overhead
    + 12 // IEND chunk
    

    Compression "quality" doesn't enter into this.

    Most applications will probably separate the IDAT chunk into smaller chunks, typically 8 kbytes each, so in the case of a 350x350 image there would be 44 IDAT chunks, so add 43*12 for IDAT chunk overhead.

    As a check, a 1x1 16-bit RGB image can be written as a 72-byte PNG, and a 1x1 8-bit grayscale image is 67 bytes.

    If the image is interlaced, or has any ancillary chunks, or has an alpha channel, it will naturally be bigger.