Search code examples
compressionimagingpagespeedgoogle-pagespeed

How does Google's Page Speed lossless image compression work?


When you run Google's PageSpeed plugin for Firebug/Firefox on a website it will suggest cases where an image can be losslessly compressed, and provide a link to download this smaller image.

For example:

This applies across both JPG and PNG filetypes (I haven't tested GIF or others.)

Note too the Flickr thumbnails (all those images are 75x75 pixels.) They're some pretty big savings. If this is really so great, why aren't Yahoo applying this server-side to their entire library and reducing their storage and bandwidth loads?

Even Stackoverflow.com stands for some very minor savings:

I've seen PageSpeed suggest pretty decent savings on PNG files that I created using Photoshop's 'Save for Web' feature.

So my question is, what changes are they making to the images to reduce them by so much? I'm guessing there are different answers for different filetypes. Is this really lossless for JPGs? And how can they beat Photoshop? Should I be a little suspicious of this?


Solution

  • If you're really interested in the technical details, check out the source code:


    For PNG files, they use OptiPNG with some trial-and-error approach

    // we use these four combinations because different images seem to benefit from
    // different parameters and this combination of 4 seems to work best for a large
    // set of PNGs from the web.
    const PngCompressParams kPngCompressionParams[] = {
      PngCompressParams(PNG_ALL_FILTERS, Z_DEFAULT_STRATEGY),
      PngCompressParams(PNG_ALL_FILTERS, Z_FILTERED),
      PngCompressParams(PNG_FILTER_NONE, Z_DEFAULT_STRATEGY),
      PngCompressParams(PNG_FILTER_NONE, Z_FILTERED)
    };
    

    When all four combinations are applied, the smallest result is kept. Simple as that.

    (N.B.: The optipng command line tool does that too if you provide -o 2 through -o 7)


    For JPEG files, they use jpeglib with the following options:

     JpegCompressionOptions()
         : progressive(false), retain_color_profile(false),
           retain_exif_data(false), lossy(false) {}
    

    Similarly, WEBP is compressed using libwebp with these options:

      WebpConfiguration()
          : lossless(true), quality(100), method(3), target_size(0),
            alpha_compression(0), alpha_filtering(1), alpha_quality(100) {}
    

    There is also image_converter.cc which is used to losslessly convert to the smallest format.