Compression in practice

Lossy and lossless compression

Two families of compression

All the methods seen so far are lossless: after decompression, you get back the original file bit for bit. This is essential for a text, a program, a spreadsheet — the slightest alteration would be an error. But for a sound, an image or a video, we can afford to lose a little: this is lossy compression.

The idea of controlled loss

Lossy compression deliberately removes information that our senses perceive poorly. MP3 removes sounds that another frequency masks to the ear; JPEG smooths out fine details that the eye has trouble distinguishing. We accept a small degradation in exchange for a huge gain in size.

Comparison of the two families:

LOSSLESS (ZIP, PNG, gzip, FLAC)
  file -> compress -> decompress = IDENTICAL file (bit for bit)
  use: text, code, archives, technical images

LOSSY (JPEG, MP3, MP4)
  file -> compress -> decompress = CLOSE file (but not identical)
  use: photos, music, video; much larger size gain

The quality/size trade-off

With lossy compression, you choose a quality level: the more you compress, the smaller the file, but the more visible or audible the degradation becomes. At low rates, the loss is imperceptible; at high rates, the famous "artifacts" appear (blur, blocks, metallic sounds).

Choosing the right method

The right choice depends on the use. You never archive source code as JPEG (that would be absurd and destructive). Nor do you store thousands of photos as lossless PNG if a JPEG ten times lighter is good enough for the eye. Lossless for what must stay exact, lossy for what is meant for the senses.

Classic pitfall

Loss is irreversible and cumulative: every time you re-save a JPEG, you add artifacts to it, with no way back to the original. Re-saving an image several times with lossy compression degrades it progressively, like a photocopy of a photocopy. To edit, always work on a lossless source, and only apply lossy compression at the very end.