PHP’s imagepng function and its performance have a very interesting fact. When you think compression in imagepng comes with a quality-loss or you should always choose one of the highest compression then you’ll get now new information.

In the documentation of this function we’re seeing following quality option:

    Compression level: from 0 (no compression) to 9.

This is a bit misleading as most people think image compression comes always with a quality-loss. But in PNGs you don’t get a quality-loss through compressing. Period.

This means, if you call imagepng($image, null, 0) or imagepng($image, null, 9) you’ll get the exact same quality. The only difference is the file size.

The interesting part is here now: If it’s worth to compress PNGs?

I made a little test scenario on my machine with a test image (JPEG) that has a dimension of 1880 x 2816px and a file size of 1.651.882 bytes (1,7 MB).

My code now just opens the image and prints it as a PNG.

    $image = imagecreatefromjpeg('test.jpg');
    header('Content-Type: image/png');
    imagepng($image, null, 9);

So, what do you think is the result?

This means, my machine (MacBook Retina, Intel i7) tooks over 22 seconds for just one image! That is really a CPU burner!

So, let’s see how fast it is with no compression.

imagepng($image, null, 0):

This one tooks almost a second, but did send a 20 MB image.

So, I tested through all compression modes and created a table:

CompressionSecondsFileSize00.920 MB11.08 MB21.127.8 MB31.57.5 MB41.66.8 MB52.46.8 MB64.56.7 MB76.56.6 MB815.16.5 MB921.86.5 MB

As we can see in this table the compression is way to inefficient above 4+, but at the same time we see that the first and second compression level are almost for free.

What we learned

It is worth to compress PNGs, but:

Never use a compression value of 0 and never use compression modes above 6-7.