Thursday, May 17, 2012

Image Optimization

Recently we did pngout for more than 2000 files, but few of them could not be optimized due to bit depth is 64 or null. However, we have not covered other image types like JPEG, GIF. There are a lot of discussions and talks about image optimization for web performance. In our project so far, we just started the first step, but we followed 80/20 rule to optimize our website.

Generally speaking, image optimization has 2 categories: lossless and lossy.
  • Lossless Image Compression: Remove surplus info from image (Smush.it)
  • Lossy Image Compression: Match image quality to screen resolution

The safe way and easy way is to do lossless image optimization during build process and development phase. There are some high level guidelines for this optimization effort:

  • Don't use GIF unless you need animated GIF
  • Crush PNG (pngout)
  • Crush JPG (jpegtran)
  • Know PNG24 to PNG8 Conversion Guidelines
  • Know the time to choose JPG over PNG (Don't use PNG for everything)
  • Combine images (csssprite/spriteMe)
  • Compress favicon
  • Crop and compress user uploaded avatar

PNG or JPG?

  • PNG is a lossless compression format
  • JPG doesn't support transparency
  • PNG works best for vector type graphics with hard lines. 
  • JPG works best for anything with complex gradients like photo, screenshot etc
  • Use imagemagick to batch convert PNG to JPG
For more info about PNG vs JPG, check out PNG vs JPG: 6 simple lessons you can learn from our mistakes

Optimize PNG file
  • color depth
    Color depth can range from 1 to 64 bits per pixel, reduce color depth can reduce file size
  • ancillary chunks
    PNG supports metadata—remove it can reduce file size
  • interlacing
    As each pass of the Adam7 algorithm is separately filtered, this can increase file size
  • filter
    The choice of filter is potentially very variable and impacting file size
  • compression
    DEFLATE compressors can produce smaller files.

As some tools are PNG-specific, while others only optimize DEFLATE, in general one must use a combination of 2 tools in sequence for optimal compression: one which optimizes filters (and removes ancillary chunks), and one which optimizes DEFLATE. Most commonly, OptiPNG is used for the first (non-DEFLATE) step, and either of AdvanceCOMP or PNGOUT is used for the DEFLATE step. For more info or detailed comparison among PNG, JPEG, TIFF, check out http://en.wikipedia.org/wiki/Portable_Network_Graphics

Frequently used Tools
pngcrush
pngout
OptiPNG
ImageOptim
imgopt
Smush.it

1 comment:

  1. Btw, don't forget check out http://www.slideshare.net/stoyan/image-optimization-7-mistakes, one presentation Stoyan did ~4 years ago, but it is very useful guidelines with testing data.

    ReplyDelete