Files can be huge, and networks and disks are finite. Compression makes a file smaller so it downloads faster and takes less space. The clever part is doing this without throwing away anything you need — or, when you can afford it, throwing away only what you'll never miss. There are two families: lossless and lossy.
Lossless compression
Lossless compression shrinks a file so it can be restored exactly — every original bit comes back. It works by spotting and removing redundancy (repetition), like writing "×6" instead of a word six times. Perfect for text, spreadsheets and program code, where a single changed character matters. Formats: PNG, FLAC, ZIP.
Lossy compression
Lossy compression goes further by permanently discarding data the human eye or ear is unlikely to notice — subtle colour shades, or sounds masked by louder ones. The file is much smaller but cannot be perfectly restored. Ideal for photos, music and video, where "good enough" is fine. Formats: JPEG, MP3, MP4.
| Lossless | Lossy | |
|---|---|---|
| Original restored? | Exactly | No — data lost |
| File size | Smaller | Much smaller |
| Best for | text, code | photos, audio, video |
| Examples | PNG, FLAC, ZIP | JPEG, MP3, MP4 |
Run-length encoding (RLE)
RLE is a simple lossless method: a run of identical values is replaced by one copy of the value plus a count. It shines on data with long repeats, such as plain-coloured image regions.
Six A's, four B's, two C's. Encoded as pairs (count, value): 6A 4B 2C.
The original is 12 characters; the code stores three count-value pairs. Decoding is exact, so it is lossless.
Huffman coding — the idea
Huffman coding is a cleverer lossless method. Instead of giving every character the same number of bits, it gives the most frequent characters the shortest codes and rare ones longer codes — like using a quick nickname for the friend you mention most. Overall the message needs fewer bits, with no information lost.
Tip: match the method to the data. If losing anything is unacceptable (text, code, medical scans) choose lossless; if the goal is the smallest possible file and slight quality loss is fine (streaming, web photos) choose lossy.