Lossy compression is a good way to squeeze extra bytes out of your GIFs and PNGs. Lossy compression changes pixel patterns to match other pixel patterns to allow more efficient compression. You can apply lossy compression to the entire image, or selectively using weighted optimization with alpha masks for less important areas of your images (see Figure 1). Although the term sounds catchy, it should not be confused with the lossy compression used in JPEG compression.
What Is Lossy Compression?
Lossy compression is actually a misnomer for GIFs and PNGs. The compression algorithms used in GIFs and PNGs (LZW and Deflate) are lossless, so there is no loss of data when compressing these palette-based formats. The lossiness comes in when a graphics program automatically prefilters or alters the image to compress more efficiently. The loss of data occurs in the prefiltering phase by increasing redundant patterns along scan lines to improve compression (see Figure 2). Lossy compression has become a shorthand, yet somewhat misleading, phrase for this process.
16 colors = 2,464 bytes | Lossy 12% = 2,425 bytes | Lossy 60% = 1,468 bytes |
---|
How Does Lossy Compression Work?
The compression algorithm used in GIFs is LZW. LZW essentially looks for identical patterns of pixels along scan lines. If LZW finds an identical pattern later in the image it substitutes a token referring back to the original pattern (within a sliding window, which we’ll ignore). The more identical patterns of pixels, the smaller the file. Lossy compression simply helps the process along, by intelligently tweaking pixel values to match other patterns along scan lines. The more “lossy” compression you apply, the more programs like ImageReady and Fireworks scramble your scan lines. At lower settings, lossy compression is barely noticeable for most images. As you increase the degree of “lossiness” the effect becomes more pronounced (see Figure 3).
Conclusion
Lossy compression allows you to squeeze more bytes out of critical GIF and PNG images. By applying judicious amounts of lossy compression to GIFs and PNGs you can further optimize the size of your images destined for the web.
Further Reading
- Adobe
- Makers of Photoshop and Imageready which includes lossy compression.
- Macromedia
- Makers of Fireworks which includes lossy compression.
- Lossy PNG
- Ed Avis has released a modified zlip library that performs “approximate matches of repeated strings” which can be used for lossy PNGs.
- Graphics: Use Weighted Optimization
- Weighted optimization or regional compression applies different degrees of compression to different areas of your image. By varying the quality within images you can improve file size.
- Optimizing Web Graphics
- Chapter summary from Speed Up Your Site, shows how to correct, optimize, and compress images for minimum file size and maximum quality.