Sub topic 7
Lossy and lossless compression
This chapter assumes you know that a raster image is a grid of pixels, that each pixel holds color values, and that file extensions like .jpg and .png name different formats. You do not need to know any algorithm details. By the end you should be able to explain what compression does, tell the two families apart, and predict which one damages an image.
Why compression exists
A raster image stores one color value per pixel. The size of an uncompressed image follows directly from its dimensions and its color depth.
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 uncompressedA single full-HD photo would take about 5.9 MiB. A page with ten of them would ship almost 60 MiB before any text loads. Compression reduces the number of bytes needed to store or send the same picture.
Vector files are usually small already, because they store shape descriptions instead of pixels. Compression matters most for raster images, so this chapter focuses on them.
What compression does
Compression is a method of encoding data so it takes fewer bytes. A compressor (encoder) turns the original pixel data into a smaller stream. A decompressor (decoder) turns that stream back into pixels for display or editing.
Compression works because images contain redundancy and detail the eye barely notices.
- Redundancy: Neighboring pixels often have the same or similar colors. A blue sky is thousands of nearly identical values.
- Predictability: Patterns repeat, such as rows of the same flat color or repeated textures.
- Perceptual limits: Human vision is less sensitive to small color changes than to small brightness changes, and less sensitive to fine detail in busy areas.
The first two are used by lossless methods. The third is used by lossy methods.
Lossless compression
Lossless compression shrinks a file in a way that can be exactly reversed. After decoding, every pixel has the same value as in the original. Nothing is lost, only stored more efficiently.
Two common techniques show the idea.
Run-length encoding
Run-length encoding (RLE) replaces a run of identical values with a count and one value. A row of 40 white pixels followed by 5 black pixels can be written as "40 white, 5 black" instead of 45 separate entries.
def rle_encode(values):
"""Compress a list into (value, count) pairs."""
if not values:
return []
runs = []
current = values[0]
count = 1
for v in values[1:]:
if v == current:
count += 1
else:
runs.append((current, count))
current = v
count = 1
runs.append((current, count))
return runs
def rle_decode(runs):
"""Rebuild the original list from (value, count) pairs."""
out = []
for value, count in runs:
out.extend([value] * count)
return out
row = ["W"] * 40 + ["B"] * 5
encoded = rle_encode(row)
print(encoded) # [('W', 40), ('B', 5)]
print(rle_decode(encoded) == row) # TrueThe final check prints True, which is the defining property of lossless compression: decoding returns exactly what went in.
RLE works well on flat-color graphics and poorly on photographs. In a photo, adjacent pixels rarely match exactly, so runs are short and the encoded form can be larger than the original.
Dictionary and entropy methods
PNG uses a method called DEFLATE, which combines two ideas. It finds repeated sequences of bytes and replaces later copies with references to earlier ones. It then gives frequent values shorter codes than rare ones. PNG also applies a filter step first, which stores each pixel as a difference from its neighbors. Differences tend to be small and repetitive, so they compress better than raw values.
You do not need to implement these. What matters is that all of these steps are reversible.
Lossy compression
Lossy compression discards some information permanently to reach a smaller size. After decoding, the pixels are close to the original but not identical. The goal is that the difference is hard or impossible to see at normal viewing sizes.
JPEG is the standard example. In simplified form, it does the following.
- Convert the color from RGB to a brightness channel and two color channels.
- Reduce the resolution of the color channels (chroma subsampling), since the eye is less sensitive to color detail.
- Split the image into 8×8 pixel blocks.
- Transform each block into frequency components, which separate broad changes from fine detail.
- Quantize the components. This means rounding them to coarser steps, and it is the step that discards information.
- Compress the result losslessly.
Step 5 is where the loss happens. A higher quality setting rounds less, so the file is larger and closer to the original. A lower setting rounds more, so the file is smaller and shows more damage.
Compression artifacts
Visible damage from lossy compression is called an artifact. The common ones are below.
| Artifact | What you see | Typical cause |
|---|---|---|
| Blocking | Visible 8×8 squares, often in smooth gradients | Low JPEG quality |
| Ringing (mosquito noise) | Fuzzy halos around sharp edges and text | Quantizing high-frequency detail |
| Color bleeding | Colors smearing across edges | Chroma subsampling |
| Banding | Stripes in a gradient instead of a smooth fade | Too few levels after rounding |
Artifacts are most visible on sharp edges, text, thin lines and flat colors. They are least visible in busy photographic texture, which hides the errors. This is why JPEG suits photographs and does badly on screenshots and logos.
Comparing the two families
| Property | Lossless | Lossy |
|---|---|---|
| Pixels after decoding | Identical to the original | Approximate |
| Typical size reduction on photos | Modest | Large |
| Typical size reduction on flat graphics | Large | Large, but with visible artifacts |
| Repeated saving | No quality change | Quality degrades each time |
| Quality control | Usually none, or only an effort setting | A quality slider trades size against fidelity |
| Common raster formats | PNG, GIF, lossless WebP | JPEG, lossy WebP |
The size gap on photographs is the main reason lossy formats exist. Natural photos have noise and fine variation, so lossless methods find little repetition to exploit. Lossy methods can drop that variation and shrink the file many times over.
Some formats support both modes. WebP can be saved either way. GIF is lossless in how it stores pixels, but it limits an image to 256 colors, so converting a photo to GIF loses information in a separate step called color quantization. The compression stage itself does not cause that loss. This distinction matters when you diagnose why an image looks wrong.
Measuring the trade-off
Compression is a trade among three things: file size, visual quality, and processing cost. You can measure the first directly. The following script saves one generated image at several JPEG quality levels and prints the resulting file sizes. It needs the Pillow library (pip install pillow).
import io
import random
from PIL import Image
random.seed(1)
width, height = 400, 300
# Build a noisy gradient so the image resembles photographic detail.
img = Image.new("RGB", (width, height))
pixels = img.load()
for y in range(height):
for x in range(width):
base = int(255 * x / width)
noise = random.randint(-20, 20)
r = max(0, min(255, base + noise))
g = max(0, min(255, 255 - base + noise))
b = max(0, min(255, int(255 * y / height) + noise))
pixels[x, y] = (r, g, b)
for quality in (95, 75, 50, 25, 10):
buffer = io.BytesIO()
img.save(buffer, format="JPEG", quality=quality)
print(f"quality {quality:>2}: {buffer.tell():>6} bytes")
png_buffer = io.BytesIO()
img.save(png_buffer, format="PNG")
print(f"PNG (lossless): {png_buffer.tell():>6} bytes")The exact numbers depend on your Pillow version, but the pattern is stable. File size falls as the quality number falls, and the lossless PNG of this noisy image is larger than every JPEG. If you replace the noisy gradient with a flat fill, the PNG shrinks to a tiny file and often beats the JPEG. Try that change and compare.
Common mistakes
- Saving a logo or screenshot as JPEG. Sharp edges and text produce ringing. Use PNG, or SVG for a logo.
- Saving a photo as PNG for the web. The file is correct but needlessly large. Use JPEG or WebP unless you need exact pixels or transparency.
- Re-saving JPEGs repeatedly. Quality drops each generation. Work from a master.
- Believing "lossless" means "small". Lossless only promises exact reconstruction. A lossless photo can still be several times larger than a good JPEG.
- Believing a high quality number means lossless. JPEG at quality 100 is still lossy. It discards less, but it is not an exact copy.
- Judging quality at a zoomed-out view. Check artifacts at 100% zoom, the size at which the image will actually be shown.
Where vector files fit
Vector formats are not usually described as lossy or lossless in the same way, because they do not hold pixels. An SVG is text describing shapes, and it can be compressed with a general-purpose lossless method such as gzip when a server sends it. The result decodes to the same text. The shapes themselves are stored exactly. A loss occurs only when a vector is rasterized to pixels, or when a tool simplifies paths and removes points, which reduces precision on purpose.
Summary
Compression reduces file size by exploiting redundancy and the limits of human vision. Lossless methods such as RLE and DEFLATE reverse exactly, so repeated saving is safe, but they shrink photographs only modestly. Lossy methods such as JPEG discard detail through quantization, which gives much smaller photo files at the cost of artifacts and cumulative damage. Pick the family by content: flat graphics, text and masters belong in lossless formats, and finished photographs for delivery often belong in lossy ones.
Exercise
A designer exports a company logo with sharp text and flat colors as a JPEG at quality 60. The edges look fuzzy. Name the artifact, explain why it appears, and give two better format choices with a reason for each.
Show answer
The artifact is ringing (mosquito noise) around sharp edges, possibly with color bleeding. JPEG quantizes the high-frequency components that describe sharp edges, so the edges are approximated and leave halos. PNG is a good choice because it is lossless and stores the flat colors and edges exactly, usually in a small file. SVG is better still for a logo, because it stores the shapes as paths and stays sharp at any size.
Exercise
You open a JPEG photo, brighten it, and save it as JPEG at quality 85. You repeat this ten times. Explain what happens to the image and describe a workflow that avoids the problem.
Show answer
Each save runs the lossy quantization step again on data that was already approximated, so errors accumulate and artifacts such as blocking and banding grow. A better workflow keeps the original, or a lossless master such as PNG or a layered editing file, makes all edits on it, and exports a JPEG copy only once at the end.
Exercise
Run the RLE example on a row made of 45 alternating values, "W", "B", "W", "B" and so on. Is the encoded form smaller than the original? What does this tell you about using RLE on photographs?
Show answer
No. Every run has length 1, so the encoded form has 45 pairs, which is larger than the 45 plain values. Photographs rarely contain long runs of identical pixels, so RLE alone compresses them poorly, which is why photographic formats use other methods and often accept lossy compression.