Google PageSpeed & ImageMagick JPG compression

StackOverflowNewbie picture StackOverflowNewbie · Oct 10, 2010 · Viewed 9.9k times · Source

Given a user uploaded image, I need to create various thumbnails of it for display on a website. I'm using ImageMagick and trying to make Google PageSpeed happy. Unfortunately, no matter what quality value I specify in the convert command, PageSpeed is still able to suggest compressing the image even further.

Note that http://www.imagemagick.org/script/command-line-options.php?ImageMagick=2khj9jcl1gd12mmiu4lbo9p365#quality mentions:

For the JPEG ... image formats, quality is 1 [provides the] lowest image quality and highest compression ....

I actually even tested compressing the image using 1 (it produced an unusable image, though) and PageSpeed still suggests that I can still optimize such image by "losslessly compressing" the image. I don't know how to compress an image any more using ImageMagick. Any suggestions?

Here's a quick way to test what I am talking about:

assert_options(ASSERT_BAIL, TRUE);

// TODO: specify valid image here
$input_filename = 'Dock.jpg';

assert(file_exists($input_filename));

$qualities = array('100', '75', '50', '25', '1');
$geometries = array('100x100', '250x250', '400x400');

foreach($qualities as $quality)
{
    echo("<h1>$quality</h1>");
    foreach ($geometries as $geometry)
    {
        $output_filename = "$geometry-$quality.jpg";

        $command = "convert -units PixelsPerInch -density 72x72 -quality $quality -resize $geometry $input_filename $output_filename";
        $output  = array();
        $return  = 0;
        exec($command, $output, $return);

        echo('<img src="' . $output_filename . '" />');

        assert(file_exists($output_filename));
        assert($output === array());
        assert($return === 0);
    }

    echo ('<br/>');
}

Answer

Sjoerd picture Sjoerd · Oct 10, 2010
  • The JPEG may contain comments, thumbnails or metadata, which can be removed.
  • Sometimes it is possible to compress JPEG files more, while keeping the same quality. This is possible if the program which generated the image did not use the optimal algorithm or parameters to compress the image. By recompressing the same data, an optimizer may reduce the image size. This works by using specific Huffman tables for compression.

You may run jpegtran or jpegoptim on your created file, to reduce it further in size.