Sub topic 8
Common raster formats
This chapter covers the four raster formats you will meet most often: JPEG, PNG, GIF and WebP. It assumes you know that a raster image is a grid of pixels, that compression can be lossy or lossless, and that color depth is the number of bits stored per pixel. If any of that is unclear, review the earlier chapters on the raster model, color depth and compression first.
What a file format decides
A raster file format is a set of rules for storing a pixel grid in a file. Every format makes choices on five points:
- Compression type. Lossy formats discard detail to save space. Lossless formats store everything and can rebuild the exact original pixels.
- Color capacity. Some formats allow millions of colors per pixel. Others allow only 256 colors in total.
- Transparency. A format may support no transparency, on/off transparency, or partial transparency (an alpha channel).
- Animation. Some formats can hold several frames.
- Metadata. Some formats can carry camera data, color profiles, and so on.
No format wins on all five. Picking one means matching these choices to the content and the destination.
A useful baseline is the uncompressed size of an image. A 1920 by 1080 image at 3 bytes per pixel is about 5.9 MiB before compression.
width, height = 1920, 1080
bytes_per_pixel = 3 # 8 bits each for red, green and blue
size_bytes = width * height * bytes_per_pixel
print(size_bytes) # 6220800 bytes, about 5.9 MiB uncompressedEvery format below is, in effect, a different way to shrink that number.
JPEG
JPEG (Joint Photographic Experts Group, extensions .jpg and .jpeg) is a lossy format designed for photographs.
How it works
JPEG converts the image into brightness and color components. It then splits the image into 8 by 8 pixel blocks and stores each block as a mix of smooth patterns. Fine detail that the eye barely notices is rounded away. The encoder also stores color at lower resolution than brightness, because people notice brightness changes more than color changes. A quality setting, usually 0 to 100, controls how much is discarded.
Strengths
- Very small files for photographs with smooth gradients and natural texture.
- 24-bit color (about 16.7 million colors).
- Supported everywhere.
Limitations and common errors
- No transparency. A JPEG always has a solid background.
- Artifacts on sharp edges. Text, line art and flat-color graphics show ringing: fuzzy specks around edges.
- Blockiness at low quality. The 8 by 8 blocks become visible in smooth areas.
- Generation loss. Each time you open a JPEG, edit it, and save it again as JPEG, it is re-encoded and loses more detail. Keep an original and export from it once.
PNG
PNG (Portable Network Graphics, .png) is a lossless format.
How it works
PNG first applies a filter that predicts each pixel from its neighbors and stores only the difference. It then compresses the result with the Deflate algorithm. Because areas of flat color produce long runs of identical differences, they compress very well. Photographs do not, because noise and texture make neighboring pixels unpredictable.
Variants
| Variant | Colors | Transparency |
|---|---|---|
| PNG-8 (indexed) | Up to 256, from a palette | On/off, or limited per-palette-entry alpha |
| PNG-24 | About 16.7 million | None |
| PNG-32 | About 16.7 million | Full 8-bit alpha channel |
Strengths
- Exact reproduction of pixels, so repeated saving causes no loss.
- Partial transparency, which allows soft shadows and anti-aliased edges over any background.
- Sharp text, screenshots, interface elements and flat-color graphics.
Limitations
- Photographs produce files several times larger than the equivalent JPEG.
- Standard PNG does not support animation. APNG (Animated PNG) is an extension that does, and modern browsers handle it.
GIF
GIF (Graphics Interchange Format, .gif) is an older lossless-per-frame format. It is now used mostly for short animations.
How it works
GIF stores each frame as an indexed image with a palette of at most 256 colors, compressed with the LZW algorithm. Frames play in sequence with a delay between them, and the file can loop.
Strengths
- Animation that plays almost anywhere without extra code.
- Simple on/off transparency.
Limitations
- 256-color limit per frame. Photographs turn into banding or visible dither patterns (a scatter of dots that imitates missing colors).
- No partial transparency. A pixel is either fully visible or fully transparent, so edges over varied backgrounds show a halo (a fringe of the original background color).
- Large animations. Without inter-frame video compression, a few seconds of animation can reach many megabytes. Short video formats are usually smaller.
WebP
WebP (.webp) was designed by Google as a single replacement for JPEG, PNG and GIF on the web.
How it works
WebP has two compression modes inside one container:
- Lossy mode uses prediction techniques borrowed from video coding. It usually produces smaller files than JPEG at similar visual quality.
- Lossless mode uses prediction and entropy coding tuned for graphics. It usually produces smaller files than PNG.
Both modes can include an alpha channel, so a lossy WebP can have partial transparency, which JPEG cannot. WebP also supports animation.
Strengths
- One format covers photographs, graphics, transparency and animation.
- Smaller files than JPEG or PNG for equivalent quality, commonly by a quarter to a third.
Limitations
- Older software, some email clients and some image editors may not open
.webpfiles. All current major browsers support it, but you may still need a fallback for old environments. - Encoding is slower than JPEG encoding.
- It is mainly a delivery format. Many print workflows and design tools expect JPEG, PNG or TIFF.
Comparing the formats
| Feature | JPEG | PNG | GIF | WebP |
|---|---|---|---|---|
| Compression | Lossy | Lossless | Lossless (but limited to 256 colors) | Lossy or lossless |
| Colors | About 16.7 million | Up to about 16.7 million | 256 per frame | About 16.7 million |
| Transparency | No | Full alpha | On/off only | Full alpha |
| Animation | No | Only via APNG | Yes | Yes |
| Best for | Photographs | Screenshots, graphics, UI | Simple animations | Web delivery of all types |
Choosing a format
Work through these questions in order.
- Does it need to animate? Prefer animated WebP, or a short video, for size. Use GIF only when you need maximum compatibility.
- Does it need partial transparency? Use PNG or WebP.
- Is it a photograph or other image with continuous tones? Use JPEG or lossy WebP.
- Is it a screenshot, text, or flat-color graphic? Use PNG or lossless WebP.
- Do you need a pixel-exact copy for further editing? Use PNG, or another lossless format.
Compare formats by testing
File size depends on the content, so measure with your own images. This script saves one image in several formats and prints the sizes. It uses the Pillow library (pip install pillow) and assumes a file named photo.png exists beside the script.
import os
from PIL import Image
src = Image.open("photo.png").convert("RGB")
src.save("out.jpg", "JPEG", quality=85)
src.save("out.png", "PNG", optimize=True)
src.save("out_lossy.webp", "WEBP", quality=80)
src.save("out_lossless.webp", "WEBP", lossless=True)
for name in ["out.jpg", "out.png", "out_lossy.webp", "out_lossless.webp"]:
print(f"{name}: {os.path.getsize(name)} bytes")Run it once on a photograph and once on a screenshot. For the photograph, JPEG and lossy WebP should be far smaller than PNG. For the screenshot, PNG and lossless WebP should win, and JPEG will show ringing around the text.
Using the formats on the web
Browsers load all four formats through the same img element. Always give an alt attribute and the pixel dimensions, so the page does not shift while the image loads.
<img src="logo.svg" alt="Company logo" width="120">
<img src="photo.jpg" alt="Mountain lake at sunrise" width="600" height="400">To offer WebP with a fallback, use the picture element. The browser takes the first source it supports.
<picture>
<source srcset="photo.webp" type="image/webp">
<img src="photo.jpg" alt="Mountain lake at sunrise" width="600" height="400">
</picture>Common errors
- Saving a logo or screenshot as JPEG. The result has fuzzy edges. Use PNG, or a vector format for logos.
- Saving a photograph as PNG. The file is far larger than needed. Use JPEG or lossy WebP.
- Re-saving JPEGs repeatedly. Quality drops each time. Export from the original once.
- Using GIF for photographic animation. The result is large and shows banding. Use animated WebP or video.
- Enlarging an image in a format-conversion step. No format recovers detail that is not in the pixels. Converting a small JPEG to PNG makes the file bigger but does not improve it.
- Assuming transparency survives. Converting a transparent PNG to JPEG fills the transparent area with a solid color, often black or white.
Exercise
A designer exports a company's flat-color logo with a soft drop shadow as a JPEG at quality 90, then places it on a colored banner. The edges look fuzzy and a white box appears around the logo. Name the two problems with the format choice and give a better choice.
Show answer
JPEG is lossy, so it produces ringing artifacts around sharp edges and flat colors. JPEG also has no transparency, so the background is solid white and shows as a box on the colored banner. PNG (with a full alpha channel) or lossless WebP fixes both problems, because they preserve edges exactly and support partial transparency for the shadow. A vector format such as SVG would be better still for the logo itself, but the soft shadow still needs partial transparency.
Exercise
You must publish a 4-second looping animation of a photographic scene on a web page. Why is GIF a poor choice, and what would you use instead?
Show answer
GIF is limited to 256 colors per frame, so a photographic scene shows banding or dithering. GIF also lacks inter-frame video compression, so the file becomes very large. Animated WebP is typically smaller and supports more colors and partial transparency. A short looping video is usually smaller still.