Insight

Optimizing PNG Images for Web Sites

By Steve Souders, Stoyan Stefanov and Nicole Sullivan
Excerpted from Even Faster Web Sites: Performance Best Practices for Web Developers (O'Reilly)

Dateline: June 29, 2009
More Insight articles

The single most important thing you can do to improve performance is put your site on a diet—take off (and keep off) all the bytes you put on under the stress of chasing the next killer feature. Optimizing images is one way to do just that. Historically, the question of which features to include was considered a business rather than an engineering decision, so page weight has rarely been discussed in performance circles, and yet it is extremely important to overall response time.

Response time for web pages is almost exactly correlated to page weight, and images tend to account for half of the size of typical web pages (see below). Most importantly, images are an easy place to improve performance without removing features. Often, we can make substantial improvements in the size of an image with little to no reduction in quality.



Images as a percentage of page weight for the Alexa top 10 global web sites


We'll focus on nonlossy optimizations, which result in a smaller overall file size with no loss in quality. Pixel for pixel, the visual quality of the original and final images is the same.

If you don’t optimize images, you send extra data over the wire that adds nothing to the user experience. It seems like a no-brainer to follow the practices we’ll recommend, but image optimization falls in the blurry space between engineering and design, and has historically been a neglected part of the performance puzzle.

The PNG Format

PNG (Portable Network Graphics) was created to address shortcomings of the GIF format and its patent complications. In fact, the joke goes that PNG is a recursive acronym that stands for “PNG is Not GIF.” Here are some of its features:

Truecolor and Palette PNGs
The PNG format has several subtypes, but they can roughly be divided into two: palette PNGs and truecolor PNGs. You can use palette PNGs as replacements for GIFs, and you can use truecolor PNGs instead of JPEGs.

Transparency
PNG supports full alpha transparency, although there are two quirks in Internet Explorer version 6.

Animation
Although experiments and actual implementations exist, currently there’s no cross-browser support for animated PNGs.

Nonlossy
Unlike JPEG, PNG is a nonlossy format: multiple edits do not degrade quality. This makes the truecolor PNG a suitable format for storing intermediate stages of editing a JPEG.

Horizontal Scanning
Like GIFs, PNGs that have areas of horizontally repeating colors will compress better than those with vertically repeating colors.

Interlacing
PNG supports interlacing and uses an algorithm that is superior to GIF; it allows for a better “preview” of the actual image, but interlaced PNGs have bigger file sizes.

More About PNG

Let’s take a look at a few more details that will give you a better understanding of the PNG format.

PNG8, PNG24, and PNG32

You might come across the names PNG8, PNG24, or PNG32. Let’s clarify their meaning:

PNG8
Another name for palette PNG.

PNG24
Another name for truecolor PNG that has no alpha channel.

PNG32
Another name for truecolor PNG with alpha channel.

There are other variations, such as grayscale PNGs with and without alpha, but they are used much more rarely.

Comparing PNG to the Other Formats

It’s clear that GIFs are designed for graphics, JPEGs for photographs, and various types of PNGs for both. This section compares PNG to the other formats and offers some extra details about PNG.

Comparison to GIF

Except for animation support, palette PNGs have all the features of GIFs. In addition, they support alpha transparency and generally compress better, resulting in smaller file sizes. So, whenever possible, you should use PNG8 rather than GIF.

One exception is that very small images with very few colors might compress better as GIFs. But such small imagery should be part of a CSS sprite, because the “price” of an HTTP request will greatly outweigh the saving of a few bits. Chances are the sprite image will compress better as a PNG.

Comparison to JPEG

When you have an image with more than 256 colors, you need a truecolor image format—a truecolor PNG or a JPEG. JPEGs compress better and, in general, JPEG is the format for photos. But since JPEGs are lossy and there are artifacts around sharp transitions of color, there are cases when a PNG is better:

  • When the image has slightly more than 256 colors, you might be able to convert the image to PNG8 without any visible quality loss. It’s quite surprising how sometimes you can strip out more than 1,000 colors and still not notice the difference.
  • When artifacts are unacceptable—for example, a color-rich graphic or a screenshot of a software menu—a PNG is the preferred choice.

PNG Transparency Quirks

Two quirks in Internet Explorer 6 are related to PNG and transparency:

  • Any semitransparent pixels in a palette PNG appear as fully transparent in Internet Explorer 6.
  • Alpha transparent pixels in a truecolor PNG appear as a background color (most often gray).
Crushing PNGs

PNGs store image information in “chunks.” This makes the format extensible because you can add more functionality to it using custom chunks, and programs that do not understand your new extensions can safely ignore them. But most of the chunks are not needed for web display, and you can safely remove them. An additional benefit is that stripping the so-called gamma chunk actually improves the cross-browser visual results, because each browser treats gamma corrections slightly differently.

Pngcrush

Our favorite tool for PNG optimization is pngcrush. You can run it like this:

pngcrush -rem alla -brute -reduce src.png dest.png

Let’s take a look at the options:

-rem alla
Removes all chunks except the one controlling transparency (alpha).
-brute
Tries more than 100 different methods for optimization in addition to the default 10. It’s slower and most of the time doesn’t improve much. But if you’re doing this process offline, you can afford the one or two more seconds this option takes, in case it finds a way to cut the image size further. Remove this option in performance-sensitive scenarios.
-reduce
Tries to reduce the number of colors in the palette, if possible.
src.png
The source image.
dest.png
The destination (result) image.

Other PNG Optimization Tools

Pngcrush hits a pretty good middle ground that balances execution speed against optimization results. But if you want to achieve the best possible results and you’re prepared to spend a little more time on optimization, you can try some of the other tools. Results vary, depending on the image. You can even run all the tools in succession.

Notable tools include:

PNGOUT
Binary-only, Windows, closed source.
OptiPNG
Cross-platform, open source, command-line interface.
PngOptimizer
Windows, open source, GUI and command-line interfaces.

One “heavy-duty” tool is also available: PNGslim. It’s a batch file for Windows that runs a number of other tools. Its main activity is to run PNGOUT hundreds of times with different options. PNGOUT is the slowest of all the tools we’ve tried, so you should be prepared to allow PNGslim plenty of time to run—sometimes hours to optimize a single file.

Converting GIF to PNG

As we discussed, the PNG8 format supports everything that GIF does, so converting a GIF to PNG8 should result in no visible changes. You can use ImageMagick to do the conversion from the command line as simply as:

convert source.gif destination.png

You can also force the PNG8 format by using:

convert source.gif PNG8:destination.png

This is probably not necessary, since GIFs are likely to be converted to PNG8 anyway. ImageMagick picks the appropriate format based on the number of colors. Once you’ve converted the GIF to PNG, don’t forget to crush the PNG result (as shown earlier). You can also use ImageMagick’s identify utility to programmatically determine whether the GIF file contains an animation. For example:

identify -format %m my.gif

This command will simply return “GIF” for nonanimated GIFs. For GIF animations it will return a string such as “GIFGIFGIF…” repeating “GIF” once for every frame. If you’re running a script to convert files, checking for the presence of “GIFGIF” in the first six-character substring of the output will let you know you’re dealing with an animated file.



Don't miss the next Insight tip on Graphics.com. Get the free Graphics.com newsletter in your mailbox each week. Click here to subscribe.

Excerpted from Even Faster Web Sites: Performance Best Practices for Web Developers by Steve Souders. ISBN 0-596-52230-4. Copyright © 2009 Steve Souders. All rights reserved. Used with permission.





This feature comes from Graphics.com
http://www.graphics.com

The URL for this feature is:
http://www.graphics.com/modules.php?name=Sections&op=viewarticle&artid=756