138

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?

1
  • It looks like Pagespeed is now demanding lossy compression. Before the results said: "Losslessly compressing xxx.jpg could save xx kb (xx% reduction)". Now it says "Compressing xxx.jpg could save xx kb (xx% reduction)" Importantly, Google seems to request to lossily compress the smaller images only (thumbnails etc). Can anyone figure out what lossy compression tools and parameters Google is using?
    – Martin
    Commented Dec 25, 2016 at 18:40

9 Answers 9

82

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.

3
  • 3
    Specifically retain_color_profile(false) for JPEGs can be a bad idea. As extended color gamut displays become more common a clearly defined color rendition instruction becomes an ambiguous one. If the original image was sRGB encoded this will still work in some browsers (Safari, Firefox with about:config modification) while in others only actually tagged images might be color managed (default Firefox). Of course browsers without any color management capabilities won't care…
    – C.O.
    Commented Jul 15, 2013 at 18:51
  • 2
    I've been runningoptipng file.png -o7 and I'm not getting anywhere near what Google shows. Perhaps they convert to SVG when possible?
    – Nateowami
    Commented Jul 4, 2016 at 5:54
  • @Nateowami I had the same issue... for some PNGs Google does better than optipng -o7. For these you can download the optimized images from the pagespeed website itself.
    – chrisvdb
    Commented Jun 22, 2017 at 14:00
45

I use jpegoptim to optimize JPG files and optipng to optimize PNG files.

If you're on bash, the command to losslessly optimize all JPGs in a directory (recursively) is:

find /path/to/jpgs/ -type f -name "*.jpg" -exec jpegoptim --strip-all {} \;

You can add -m[%] to jpegoptim to lossy compress JPG images, for example:

 find /path/to/jpgs/ -type f -name "*.jpg" -exec jpegoptim -m70 --strip-all {} \;

To optimize all PNGs in a directory:

find /path/to/pngs/ -type f -name "*.png" -exec optipng -o2 {} \;

-o2 is the default optimization level, you can change this from o2 to o7. Notice that higher optimization level means longer processing time.

29

Take a look at http://code.google.com/speed/page-speed/docs/payload.html#CompressImages which describes some of the techniques/tools.

4
  • 1
    Thanks for the link. I guess I'm looking really to learn more about what kinds of redundancies there are in image files that can be stripped away if filesize is your primary concern. I know that info is out there on the web, I just wanted to have a nice place to collate it here on SO. Commented Mar 27, 2011 at 19:10
  • I use a custom build tool which compresses images with both optipng and pngcrush, then selects the smaller file. Still, Page Speed complains about non-optimal images. So which tool do they really use? Commented Sep 10, 2012 at 7:42
  • @Pumbaa80 You might also try advsys.net/ken/util/pngout.htm (which specifically says that it can sometimes get smaller sizes than both optipng and pngcrush).
    – Amber
    Commented Sep 10, 2012 at 7:45
  • I just found out that Page Speed indeed uses optipng, with a custom wrapper that determines the best config options. @Amber Not an option, I'm not using Windows ;) Commented Sep 10, 2012 at 7:50
15

It's a matter of trading encoder's CPU time for compression efficiency. Compression is a search for shorter representations, and if you search harder, you'll find shorter ones.

There is also a matter of using image format capabilities to the fullest, e.g. PNG8+a instead of PNG24+a, optimized Huffman tables in JPEG, etc.

Photoshop doesn't really try hard to do that when saving images for the web, so it's not surprising that any tool beats it.

See

1
  • The only answer that attempts to answer the actual question the O/P actually asked, instead of the different question "how can I compress my images the most"? lol
    – toddmo
    Commented Sep 22, 2015 at 20:53
13

To Replicate PageSpeed's JPG Compression Results in Windows:

I was able to get exactly the same compression results as PageSpeed using the Windows version of jpegtran which you can get at www.jpegclub.org/jpegtran. I ran the executable using the DOS prompt (use Start > CMD). To get exactly the same file size (down to the byte) as PageSpeed compression, I specified Huffman optimization as follows:

jpegtran -optimize source_filename.jpg output_filename.jpg

For more help on compression options, at the command prompt, just type: jpegtran

Or to Use the Auto-generated Images from the PageSpeed tab in Firebug:

I was able to follow Pumbaa80's advice to get access to PageSpeed's optimized files. Hopefully the screenshot here provides further clarity for the FireFox environment. (But I was not able to get access to a local version of these optimized files in Chrome.)

And to Clean up the Messy PageSpeed Filenames using Adobe Bridge & Regular Expressions:

Although PageSpeed in FireFox was able to generate optimized image files for me, it also changed their names turning simple names like:

nice_picture.jpg

into

nice_picture_fff5e6456e6338ee09457ead96ccb696.jpg

I discovered that this seems to be a common complaint. Since I didn't want to rename all my pictures by hand, I used Adobe Bridge's Rename tool along with a Regular Expression. You could use other rename commands/tools that accept Regular Expressions, but I suspect that Adobe Bridge is readily available for most of us working with PageSpeed issues!

  1. Start Adobe Bridge
  2. Select all files (using Control A)
  3. Select Tools > Batch Rename (or Control Shift R)
  4. In the Preset field select "String Substitution". The New Filenames fields should now display “String Substitution”, followed by "Original Filename"
  5. Enable the checkbox called “Use Regular Expression”
  6. In the “Find” field, enter the Regular Expression (which will select all characters starting at the rightmost underscore separator):

    _(?!.*_)(.*)\.jpg$

  7. In the “Replace with” field, enter:

    .jpg

  8. Optionally, click the Preview button to see the proposed batch renaming results, then close

  9. Click the Rename button

Note that after processing, Bridge deselects files that were not affected. If you want to clean all your .png files, you need reselect all the images and modify the configuration above (for "png" instead of "jpg"). You can also save the configuration above as a preset such as "Clean PageSpeed jpg Images" so that you can clean filenames quickly in future.

Configuration Screenshot / Troubleshooting

If you have troubles, it's possible that some browsers might not show the RegEx expression above properly (blame my escape characters) so for a screenshot of the configuration (along with these instructions), see:

How to Use Adobe Bridge's Batch Rename tool to Clean up Optimized PageSpeed Images that have Messy Filenames

2
  • 1
    If you use IIS, PageSpeed was recently ported to Windows and performs these same optimizations automatically. iispeed.com For best reduction though without any loss, I've been bulk converting entire directories of JPEGs using JPEGmini jpegmini.com Commented Jul 24, 2014 at 0:29
  • Seems like there is no PageSpeed Extension for Firebug anymore. Commented May 10, 2016 at 14:26
10

In my opinion the best option out there that effectively handles most image formats in a go is trimage. It effectively utilizes optipng, pngcrush, advpng and jpegoptim based on the image format and delivers near perfect lossless compression.

The implementation is pretty easy if using a command line.

sudo apt-get install trimage    
trimage -d images/*

and voila! :-)
Additionally you will find a pretty simple interface to do it manually as well.

1
2

There's a very handy batch script that recursively optimizes images beneath a folder using OptiPNG (from this blog):

FOR /F "tokens=*" %G IN ('dir /s /b *.png') DO optipng -nc -nb -o7 -full %G

ONE LINE!

1
  • 1
    FOR /F "tokens=*" %G IN ('dir /s /b *.png') DO optipng -nc -nb -o7 -full "%G" if you have spaces in your file name
    – Ned Martin
    Commented Jun 23, 2016 at 4:35
0

If you are looking for batch processing, keep in mind trimage complains if you don't have Xserver avail. In that case just write a bash or php script to do something like

<?php
    echo "Processing jpegs<br />";
    exec("find /home/example/public_html/images/ -type f -name '*.jpg' -exec jpegoptim --strip-all {} \;");
    echo "Processing pngs<br />";
    exec("find /home/example/public_html/images/ -type f -name '*.png' -exec optipng -o7 {} \;");
?>

Change options to suite your needs.

0

For windows there are several drag'n'drop interfaces for easy access.

https://sourceforge.net/projects/nikkhokkho/files/FileOptimizer/

For PNG files I found this one for my enjoyment, apparently 3 different tools wrapped in this GIU. Just drag and drop and it does it for you.

https://pnggauntlet.com/

It takes time though, try compressing a 1MB png file - I was amazed how much CPU went into this compression comparison which has to be what is going on here. Seems the image is compressed a 100 ways and the best one wins :D

Regarding the JPG compression I to feel its risky to strip of color profiles and all extra info - however - if everyone is doing it - its the business standard so I just did it myself :D

I saved 113MB on 5500 files on a WP install today, so its definately worth it!

Not the answer you're looking for? Browse other questions tagged or ask your own question.