1. Image Terminology
Graphics and Photos
- Graphics
Website logos, sketches, charts, most animations, and icons belong to graphics. These images are typically composed of continuous lines or other sharp color transitions, with a relatively small number of colors.
- Photos
Photos usually have millions of colors and contain smooth color transitions and gradients—imagine a photo of a sunset taken with a camera. Images of paintings (such as the Mona Lisa) are closer to photos than to graphics.
In terms of image formats, GIF is commonly used for graphics, while JPEG is more suitable for photos. PNG is suitable for both, and using palette PNG for graphics can even be better than GIF.
Pixels and RGB
Images are composed of pixels, which are the smallest units of information in an image. We can use different color models to describe pixels; in computer image processing, the RGB color model is the most commonly used.
In the RGB color model, a pixel is described by the amount of Red (R), Green (G), and Blue (B) it contains. R, G, and B are called components (also known as channels), and the intensity of each component ranges from 0 to 255. In HTML and CSS, we often use hexadecimal component values ranging from 00 to FF. By combining components of different intensities, different colors can be obtained. For example:
-
Red is
rgb(255, 0, 0)or hexadecimal#FF0000. -
Blue is
rgb(0, 0, 255)or hexadecimal#0000FF. -
Shades of gray likely have three identical component values, such as
rgb(238, 238, 238)or hexadecimal#EEEEEE.
True Color and Palette Image Formats
How many different colors can actually be displayed using the RGB color model? The answer is 16 million: 256 * 256 * 256 (or 2 to the 24th power) results in 16,777,216 combinations. Image formats that can support this many colors are called true color formats, such as JPEG and true color PNG.
To save space when storing image information, a technique is used to extract various colors from an image to create a table, commonly called a palette (also known as an index). With this color table, the entire image can be redrawn by re-matching the entries in the palette with each pixel.
A palette can contain any RGB color value, but the most frequently used palette image formats—GIF and PNG8—limit the palette to a maximum of 256 colors. This doesn't mean you can only choose from 256 predefined colors; on the contrary, you can choose the values you need from over 16 million colors, but a single image can contain at most 256 distinct colors.
Transparency and Alpha Channel (RGBA)
RGBA is not a completely different color model but an extension of RGB. The extra component A represents alpha transparency, with values also ranging from 0 to 255. However, different programs and libraries may define transparency as a percentage from 0% to 100% or as a value from 0 to 127. The alpha channel describes the extent to which content below the image pixel can be seen.
Suppose you have created a web page, set a background, and placed a blue image on top. If a pixel on the image has its transparency set to 0, the background below that pixel is invisible. If alpha transparency is set to the maximum (100%), the pixel on the image will be hidden, and the background will "show through." If set to a middle value, like 50%, you can see both the background and the pixel on the image simultaneously.
Interlacing
When network speeds are slow, large images are displayed line by line as they download, progressing slowly from top to bottom. To improve the user experience, some image formats support interlacing for continuously sampled images. Interlacing allows users to see a rough version of the image before it is fully downloaded, psychologically eliminating the feeling of a delayed page load.
2. Characteristics of Different Image Formats
The differences between GIF, JPEG, and PNG:
GIF
Short for Graphics Interchange Format, it is a palette-based image format with the following characteristics:
- Transparency
GIF allows for a binary (yes/no) type of transparency: each pixel is either completely transparent (contains no color) or completely opaque (contains a single color). This means it does not support alpha (variable) transparency; instead, a specific color in the palette can be marked as representing transparency, and transparent pixels are assigned this color value. Therefore, if you set transparent pixels for a GIF, it "consumes" one palette entry.
- Animation
The GIF format supports animation; an animated image consists of several frames, as if several images were contained in a single file. It is widely considered that GIF animations are annoying because they were overused in the early days of the web for things like blinking text and rotating @ signs. GIF animations still have some applications today, such as banner ads (though Flash now dominates this area) and "loading" indicators in Rich Internet Applications (RIAs).
- Lossless
GIF is lossless, meaning you can open any GIF file, make modifications, and save it without losing any quality.
- Row Scanning
When a GIF file is generated, a compression algorithm (called LZW) is used to reduce the file size. When compressing a GIF, pixels are scanned row by row from top to bottom. In this case, better compression is achieved when the image has many repeating colors horizontally. For example, a 500x10 pixel image (500px wide and 10px high) containing horizontal stripes of identical colors will result in a smaller file size than the same image rotated 90 degrees (10px wide and 500px high) with vertical stripes.
- Interlacing
GIF supports optional interlacing.
Due to its 256-color limit, GIF is not suitable for displaying photos, which require far more colors. GIF is better suited for graphics (icons, logos, and charts), but PNG8 is the optimal format for graphics. Therefore, GIF should only be used when animation is required.
The LZW lossless data compression algorithm used in the GIF format was previously protected by patents, but these patents expired in 2004, and GIF can now be used freely.
JPEG
JPEG stands for Joint Photographic Experts Group, the name of the organization that developed the standard. JPEG is the de facto standard for storing photos. Taking into account human perception of color and light intensity, this format uses various techniques to reduce the information necessary to display a picture, allowing it to store high-resolution images in highly compressed files. It has the following characteristics:
- Lossy
JPEG is a lossy format. Users can set custom quality levels, which determine how much image information is discarded. Quality levels range from 0 to 100, but even a setting of 100 involves some degree of quality loss.
When performing multiple editing operations on an image, it's best to use a lossless image format to save intermediate results and then save as JPEG only after all modifications are complete; otherwise, quality will be lost with every save.
However, a few operations are lossless, such as:
- Rotation (only in increments of 90, 180, and 270 degrees)
- Cropping
- Flipping (horizontal or vertical)
- Switching from standard to progressive mode and vice versa
- Editing image metadata
- Transparency and Animation
JPEG does not support transparency or animation.
- Interlacing
In addition to the default standard JPEG (Baseline JPEG), there is also Progressive JPEG, which supports interlacing. Internet Explorer does not render Progressive JPEG images progressively; instead, it displays them all at once when fully downloaded.
JPEG is the best format for storing photos on the web and is widely used in digital cameras. However, it is not suitable for storing graphics because the lossy compression method turns lines and sharp color transitions into "blocks."
PNG
To address the shortcomings of the GIF format and avoid the patent issues of the LZW algorithm, PNG (Portable Network Graphics) was created. In fact, people often joke that PNG stands for the recursive acronym "PNG is Not Gif." It has the following characteristics:
- True Color and Palette PNG Formats
There are several subtypes of the PNG format, but they can generally be divided into two: palette PNG and true color PNG. Palette PNG can be used as a replacement for GIF, and true color PNG can be used as a replacement for JPEG.
- Transparency
PNG supports full alpha transparency. Using this feature in Internet Explorer 6 can cause issues (transparent areas turning pinkish-blue, aliasing, etc.; for more details, see Comprehensive Expansion of PNG Background Transparency Issues in IE6).
- Animation
While experiments and practical applications exist, there is currently no cross-browser solution for animated PNG formats.
- Lossless
Unlike JPEG, PNG is a lossless image format: multiple edits do not degrade its quality. This makes true color PNG ideal for saving intermediate results during JPEG editing.
- Row Scanning
Like GIF, PNG achieves higher compression for images with repeating colors horizontally compared to those with repeating colors vertically.
- Interlacing
PNG supports interlacing and uses a better algorithm than GIF, allowing for a better "preview" of the true image. However, interlaced PNG images result in larger file sizes.
3. PNG
Classification of PNG
PNG is divided into PNG8, PNG24, and PNG32:
- PNG8
Palette PNG
- PNG24
True color PNG, but without an alpha channel.
- PNG32
True color PNG, with an alpha channel.
PNG and GIF
Except for the lack of animation support, palette PNG has all the features of GIF. Furthermore, it supports alpha transparency and typically achieves higher compression with smaller file sizes. Therefore, PNG8 should be used instead of GIF whenever possible.
One exception is very small images with very few colors, where GIF's compression might be higher. However, such small images should actually be placed in a CSS Sprite, as the overhead of HTTP requests far exceeds the small amount of bandwidth saved, and saving Sprite images in PNG format can yield higher compression.
PNG and JPEG
When the number of colors in an image exceeds 256, true color formats—true color PNG or JPEG—must be used. JPEG achieves higher compression and is generally the de facto standard for photo storage. However, because JPEG is lossy and results in blocky artifacts around sharp color transitions, PNG is more suitable in the following cases:
-
When the number of colors slightly exceeds 256, the image can be converted to PNG8 without any perceptible loss of quality. Surprisingly, sometimes you won't even notice changes after discarding more than 1,000 colors.
-
When blocky artifacts become unacceptable, such as for images with many colors or screenshots of software menus, PNG is the better choice.
4. Optimizing CSS Sprites
There are several optimization principles that can make Sprites smaller:
- Combine by Color
For example, group icons with similar color palettes together.
- Avoid Unnecessary White Space
Make images easier to handle on mobile devices.
- Arrange Elements Horizontally
Rather than vertically, as this makes the Sprite slightly smaller.
- Limit Colors to 256 or Fewer
This is the upper limit for the PNG8 format.
- Optimize Individual Images Before the Sprite
With a limited palette, it's easier to reduce the number of colors.
- Reduce Anti-Aliased Pixels via Size and Alignment
If an icon is roughly square, aligning it horizontally or vertically can often reduce the number of anti-aliased pixels.
- Avoid Diagonal Gradients
Such gradients cannot be tiled.
- Avoid Alpha Transparent Images in IE6
Keep images requiring true color alpha transparency in a separate Sprite.
- Change Gradient Colors Every 2-3 Pixels
Instead of every pixel.
- Be Careful with Logos
Logos are highly recognizable, and even tiny modifications are easily noticed.
5. Summary
Based on the above explanation, PNG generally seems to be the best choice, with GIF for animation and JPEG for high-definition photos.
Actually, the WebP format has been around for a long time (since 2010). Although its current compatibility is not perfect, there are corresponding solutions. For more information, please check The Path of Exploring WebP.
References
- "Even Faster Web Sites"
No comments yet. Be the first to share your thoughts.