01 / 21

Data
Compression

Learn how computers reduce file sizes while preserving the information that matters: the core principles behind lossless and lossy compression.

AP Computer Science Principles

What Is Data Compression?

Data compression is the process of encoding information using fewer bits than the original representation. It allows us to store more data in less space and transmit data faster over networks.

Why Compression Matters

Storage
Reduces the amount of disk space required to store files, saving cost and physical resources.
Bandwidth
Smaller files transfer faster over networks, reducing load times and data usage for users.
Efficiency
Compression enables streaming media, cloud storage, and global communication at practical scales.

Redundancy: The Key Insight

Compression works because most data contains redundancy: patterns, repeated values, or information that can be predicted. The more redundancy, the more a file can be compressed.

Original String (32 characters) AAAABBBBAAAACCCCAAAABBBBAAAACCCC compress Compressed (16 characters) 4A 4B 4A 4C 4A 4B 4A 4C

Two Types: Lossless vs. Lossy

Lossless Original = Decompressed A A 100% identical ZIP, PNG, FLAC Text, code, medical data Lossy Original ≠ Decompressed A A' Approximately identical JPEG, MP3, MP4 Photos, music, video

Key Distinctions at a Glance

Lossless Lossy
Data after decompression Identical to original Approximation of original
Typical compression ratio 2:1 to 8:1 10:1 to 50:1 or more
File formats PNG, ZIP, FLAC, GIF JPEG, MP3, MP4, AAC
Best for Text, code, medical images Photos, music, video
Reversible? Yes No

A photograph survives two different round trips

A teal-and-amber feather with fine barbs on a dark background.Fine feather edges and smooth color gradients reveal what survives compression. Lossless decoding restores the input values exactly; lossy decoding can change them.

Compare equal-size decoded images

An original feather crop is compared with lossless and lossy reconstructions at the same 64-by-64 pixel dimensions.The same 64-by-64 RGB crop passes through both processes. Lossless decoding restores every channel value; the lossy quantizer changes values while preserving the decoded dimensions. Compressed byte count and decoded pixel count measure different things.

Measuring Compression: Compression Ratio

We quantify how effective compression is using the compression ratio:

A related metric is the space savings percentage:

How to Analyze Compression

1
Identify the data type. Is it text, image, audio, or video? This determines which approach is appropriate.
2
Determine if data loss is acceptable. Must the original be perfectly reconstructed (lossless), or is an approximation fine (lossy)?
3
Look for redundancy. Repeated patterns, uniform regions, or predictable sequences all signal high compressibility.
4
Calculate the compression ratio and space savings to quantify the result and compare approaches.

Lossless Technique: Run-Length Encoding

Run-Length Encoding (RLE) replaces consecutive identical values with a single value and a count. It works best on data with long runs of the same value.

Original pixel row (16 pixels) 5 blue 3 red 6 green 2 amber RLE encoded (4 pairs = 8 values) 5B 3R 6G 2A

Lossless Technique: Huffman Encoding

Huffman Encoding assigns shorter bit codes to more frequent characters and longer codes to rare ones. Unlike fixed-length encoding (where every character uses the same number of bits), Huffman produces variable-length codes.

Character Frequencies Char Freq A 45% B 25% C 20% D 10% Huffman Codes Char Code A 0 B 10 C 110 D 111 Fixed-length: every char = 2 bits Huffman avg: 0.45(1) + 0.25(2) + 0.20(3) + 0.10(3) = 1.85 bits/char 7.5% savings over fixed-length

Count the run lengths and code bits

A black-and-white row shows runs of 7, 4, 4, 10 and 2 pixels. Below are codes A=0, B=100, R=101, C=110, D=111 and the total 23 payload bits.The five black/white runs contain 7 + 4 + 4 + 10 + 2 = 27 pixels, encoded as 7B4W4B10W2B. Separately, ABRACADABRA uses five 1-bit A codes and six 3-bit codes: 23 payload bits, plus the codebook or header.Open full diagram

Lossy Compression in Practice

Lossy compression exploits human perception limits. We cannot hear every frequency in audio or see every pixel variation in an image, so those details can be discarded.

JPEG (Images)
Removes high-frequency color detail that human eyes barely notice. Quality slider controls how much is removed.
MP3 (Audio)
Discards sounds masked by louder nearby frequencies. Psychoacoustic modeling determines what is imperceptible.
MP4/H.264 (Video)
Stores only the differences between consecutive frames, and applies spatial compression within each frame.

Track the decoded values

Original and lossless rows read 12, 25, 39, 61, 86, 120, 171, 224. The lossy row reads 0, 32, 32, 64, 96, 128, 160, 224.For these eight grayscale values, lossless decoding restores every value. Rounding to the nearest multiple of 32 changes seven values while preserving eight positions; 224 already lies on the quantization grid.Open full diagram

Example 1: Calculating Compression Ratio

A text file is 800 KB uncompressed. After applying ZIP compression, it becomes 200 KB. Find the compression ratio and space savings.

Example 2: Applying RLE

Encode the following 21-character string using Run-Length Encoding:

WWWWBBBWWWWWBBBBBWWWW

Example 3: Lossy Quality Tradeoff

A photographer has a 24 MB raw image. They save it at different JPEG quality levels:

0 5 10 15 20 24 File Size (MB) 100% 75% 50% 25% JPEG Quality Setting 23 MB 11 MB 4.5 MB 1.5 MB

Common Mistakes to Avoid

✕ Lossy is Always Bad
Lossy is not inferior: it is the right choice when perfect accuracy is unnecessary and smaller file size matters more.
✕ Compressing Twice Helps
Compressing an already-compressed file rarely reduces its size further. Redundancy has already been removed.
✕ Lossy Can Be Undone
Once data is discarded by lossy compression, it is permanently gone. You cannot recover the original from a JPEG.

Compression Summary

Concept Key Detail
Compression Ratio \(\frac{\text{Original}}{\text{Compressed}}\) Higher = smaller file
Run-Length Encoding Lossless; counts consecutive identical values Best for data with long runs
Huffman Encoding Lossless; variable-length codes by frequency Used inside ZIP, PNG, etc.
JPEG / MP3 Lossy; removes imperceptible detail Much higher compression ratios
Metadata Data about data (headers, tags) Not removed by compression

Question 1 of 5

A 12 MB audio file is compressed to 3 MB using MP3 encoding. What is the compression ratio?

Question 2 of 5

Which of the following is true about lossless compression?

Question 3 of 5

A string AAAAABBBCC is encoded using Run-Length Encoding. What is the encoded result?

Question 4 of 5

A hospital stores medical scans that doctors use for diagnosis. Which type of compression should be used?

Question 5 of 5

In Huffman encoding, which characters receive the shortest bit codes?