PHP: How to compress images without losing visible quality (automatically)? PHP: How to compress images without losing visible quality (automatically)? php php

PHP: How to compress images without losing visible quality (automatically)?


TinyPNG uses pngquant.

Pngquant has option to set desired quality, similar to JPEG. You can run something like:

<?php system('pngquant --quality=85 image.png'); ?>

Pngquant website has example code showing how to use pngquant from PHP.


For JPEG you can apply lossless jpegcrush.

JpegMini (commercial) and jpeg-archive (free) are lossy and can can automatically find a minimal good quality for a JPEG.

In PHP you can roughly estimate how much JPEG was compressed by observing how much file size changes after re-compression. File size of JPEG recompressed at same or higher quality will not change much (but will lose visual quality).

If you recompress JPEG and see file size halved, then keep the recompressed version. If you see only 10-20% drop in file size, then keep the original.

If you're compressing yourself, use MozJPEG (here's an online version).