How Image Compression Works: Lossy vs. Lossless Explained
Every day, billions of images travel across the internet — from smartphone selfies to e-commerce product shots to satellite imagery. But a raw camera file can easily hit 36 MB. How do compression algorithms shrink those files by 80–95% without making them look terrible? This guide walks through every layer of the science, from the physics of human vision to the mathematics of frequency transforms.
1. The Scale Problem — Why Compression Is Not Optional
The HTTP Archive, which crawls millions of web pages monthly, consistently reports that images account for approximately 62% of the average web page's total byte weight. In absolute terms that translates to roughly 1,100 KB of images per page load in 2025 — and that figure keeps climbing as cameras improve and design trends favour large hero imagery. Scale that across the estimated 5.5 billion internet users and the trillions of image requests served every 24 hours, and even a 10% improvement in average image compression translates to petabytes of bandwidth saved daily, lower CDN costs, and dramatically faster page loads in developing markets where 3G connectivity is still the norm.
Without compression, the web as we experience it would be unworkable. A single uncompressed 12-megapixel photograph would occupy 36 MB of bandwidth. Loading a typical e-commerce product page that shows eight product images in a gallery would require downloading over 280 MB of raw image data — roughly the size of a CD-ROM — before a single pixel rendered on screen. Even on a 100 Mbps broadband connection that would take over 22 seconds. On a 4G mobile connection averaging 20 Mbps in real-world conditions, you are looking at well over a minute of loading. Compression is not a nice-to-have optimisation; it is the foundational technology that makes visual content on the internet viable at all.
2. The Raw Bitmap Problem — Full Pixel Math
A digital image at its most primitive level is simply a rectangular grid of pixels. Each pixel in a standard 24-bit "TrueColor" image stores three separate values — one for Red, one for Green, one for Blue — each taking exactly 1 byte (8 bits), allowing 256 discrete intensity levels per channel. The total raw, uncompressed file size for any image is therefore trivially calculable: width × height × 3 bytes.
Example: 12 Megapixel camera shot
Resolution: 4,000 × 3,000 pixels
Bytes per pixel: 3 bytes (R + G + B)
Raw size = 4,000 × 3,000 × 3 = 36,000,000 bytes = 36 MB
To put that in network terms: on a typical 4G connection at 20 Mbps real-world throughput, downloading a single 36 MB raw image takes about 14.4 seconds. On 3G at 3 Mbps it balloons to 96 seconds — nearly two minutes for a single photo. Even on fast 5G at 100 Mbps it still takes nearly 3 seconds, which is longer than Google's recommended 2-second threshold for mobile page loads. This is why every image you see online has been compressed — often aggressively — before being served.
| Resolution | Raw Size | 4G Download | 3G Download |
|---|---|---|---|
| 1920 × 1080 (FHD) | 5.9 MB | 2.4 sec | 15.7 sec |
| 3840 × 2160 (4K) | 23.7 MB | 9.5 sec | 63 sec |
| 4000 × 3000 (12MP) | 36.0 MB | 14.4 sec | 96 sec |
| 6000 × 4000 (24MP) | 72.0 MB | 28.8 sec | 192 sec |
This is the fundamental motivation behind everything that follows. Every compression algorithm is, at its core, an attempt to answer one question: what information in this bitmap is truly necessary, and what can we discard or represent more compactly without the viewer noticing?
3. Lossless Compression — How PNG Does It
PNG (Portable Network Graphics) achieves compression without discarding a single pixel value, using a two-layer approach: filter prediction followed by DEFLATE entropy coding. The elegance of lossless compression is that the decompressed file is guaranteed to be a perfect bit-for-bit replica of the original. This is non-negotiable for medical imaging, architectural drawings, logos, and UI screenshots where any pixel alteration would be unacceptable.
DEFLATE: LZ77 + Huffman Coding
DEFLATE — the compression algorithm inside both PNG and ZIP — combines two techniques invented decades apart. The LZ77 sliding window algorithm scans the data stream and replaces repeated sequences with back-references: a (distance, length) pointer to where that exact sequence appeared earlier in the stream. Think of it as the compressor saying "copy the next 12 bytes from 47 bytes ago" instead of repeating those bytes verbatim. This is particularly powerful for images because adjacent pixels in real photographs tend to be similar in colour.
The simplest mental model for LZ77-style compression is run-length encoding. In a plain-text analogy, the string AAAAABBBCC can be represented as 5A 3B 2C — three tokens instead of ten characters, saving 70%. Real LZ77 is more sophisticated (it can reference any previous sequence, not just immediately preceding repeated characters), but the fundamental intuition holds.
After LZ77, the resulting token stream is passed to Huffman coding, which assigns shorter binary codewords to more-frequent symbols and longer codewords to rare ones. If the letter 'E' appears 40% of the time, it might be encoded as just 2 bits. A rare symbol appearing 0.1% of the time might need 12 bits. Overall, Huffman coding saves roughly 20–40% on top of LZ77's savings.
PNG Filter Predictors
Before DEFLATE even runs, PNG applies a row-by-row filter predictor to make the data more compressible. Instead of storing raw pixel values, PNG stores the difference between each pixel and a prediction of its value. PNG defines five filter modes — None, Sub, Up, Average, and Paeth — and the encoder can apply a different filter to each row. The Paeth filter, for instance, predicts each pixel as the nearest of its left neighbour, upper neighbour, or upper-left neighbour. In a smooth gradient, these differences are tiny numbers clustered around zero, which compress far better than the original wide-ranging pixel values. Think of it like the difference between writing down a person's exact GPS coordinates each hour versus just writing "walked 200m north, then 50m east."
💡 Pro Tip
Lossless PNG compression typically achieves only 20–50% savings on natural photographs because photographic imagery has too much high-entropy (random-looking) detail for DEFLATE to find many long repeated sequences. Save logos, UI screenshots, and diagrams as PNG. Save photographs as JPEG, WebP, or AVIF.
4. Lossy Stage 1 — Colour Space and Chroma Subsampling
Lossy compression begins not with math but with human biology. Your retina contains roughly 120 million rod cells concentrated in the peripheral visual field, which are exquisitely sensitive to brightness differences (luminance) but colour-blind. You also have approximately 6 million cone cells clustered near the fovea, which perceive colour (chrominance). This asymmetry — a 20:1 ratio of brightness-sensing cells to colour-sensing cells — is the biological fact that makes lossy compression possible.
The first step in JPEG and WebP encoding is to convert pixels from the RGB colour space (Red, Green, Blue — the native language of camera sensors and displays) to YCbCr. In YCbCr, Y represents luminance (overall brightness), Cb represents how blue the colour is relative to a mid-grey reference, and Cr represents how red. This separation is critical because it allows the encoder to treat the luminance and chrominance channels completely differently.
With the image in YCbCr, the encoder applies chroma subsampling — the most impactful single step in the entire lossy pipeline. The 4:2:0 subsampling mode, used by almost all JPEG files you encounter on the web, keeps 100% of the luminance (Y) samples but discards 75% of the colour samples, retaining only one Cb and one Cr value for every 2×2 block of four pixels. Because your visual system is so much more sensitive to brightness than colour, you almost never perceive this colour resolution halving at typical viewing distances. Chroma subsampling alone contributes roughly a 2× reduction in the raw data the DCT stage needs to process.
5. Lossy Stage 2 — The Discrete Cosine Transform
After chroma subsampling, JPEG divides the image into non-overlapping 8×8 pixel blocks and applies the Discrete Cosine Transform (DCT) to each block independently. The DCT is a mathematical transform that converts the 64 pixel values in each block from the spatial domain (raw pixel intensities at (x,y) positions) into the frequency domain (64 cosine frequency coefficients). Think of it as being similar to how a music equaliser breaks a complex sound waveform into individual frequency bands — bass, midrange, treble. The DCT does the same for image patterns: it decomposes the block into a sum of cosine waves of increasing spatial frequency.
The resulting 64 coefficients describe the block at different frequency scales. The DC coefficient (the very first one, at position 0,0) represents the average brightness of the entire 8×8 block. The remaining 63 are AC coefficients representing increasingly rapid oscillations. Smooth background gradients and sky regions produce large low-frequency coefficients and near-zero high-frequency coefficients. Sharp edges — a hard shadow line, a text glyph, fine fur texture — produce large coefficients at many frequency positions.
Quantization — Where the Data Actually Gets Discarded
The DCT itself is lossless. The lossy step happens immediately after, in quantization. The encoder divides each of the 64 DCT coefficients by a corresponding divisor from a quantization matrix, then rounds the result to the nearest integer. High-frequency coefficient positions are divided by large numbers (often 50–100 at lower quality settings), rounding many of them down to exactly zero. Low-frequency positions, which represent visually important information, are divided by smaller numbers (often 2–8) and mostly survive.
This is where JPEG's quality setting exerts its influence. A quality 95 matrix uses small divisors across the board, preserving most coefficients. A quality 50 matrix uses large divisors, zeroing out the majority of high-frequency content and producing the characteristic "blocky" JPEG artefacts on sharp edges. After quantization, the surviving non-zero coefficients (often just 5–15 out of 64 at moderate quality settings) are zig-zag scanned into a 1D sequence and compressed losslessly using Huffman or arithmetic coding to produce the final byte stream.
💡 Pro Tip
JPEG artefacts — the blocky smearing around text and sharp edges — are a direct consequence of zeroing out high-frequency DCT coefficients in those 8×8 blocks. If you see blocky halos around text in a JPEG, that is the 8×8 block boundary you are seeing. Switching to WebP or AVIF eliminates this specific artefact pattern because they use larger block sizes and better prediction.
6. Next-Gen Codecs — WebP and AVIF
JPEG was standardised in 1992. For a technology that old to still be dominant in 2025 is remarkable, but the gap between JPEG and modern codecs has grown impossible to ignore. WebP, developed by Google and released in 2010, and AVIF, based on the AV1 video codec and standardised by the Alliance for Open Media in 2019, both offer substantial improvements across every dimension: compression efficiency, colour fidelity, and feature support.
How WebP Improves on JPEG
WebP replaces JPEG's isolated 8×8 block DCT with a system borrowed from the VP8 video codec. Rather than treating each block as a self-contained unit, WebP's intra-frame prediction engine first predicts the values of each block based on its already-encoded neighbouring blocks, then only encodes the residual (prediction error). Because adjacent regions in natural photographs tend to be similar, the residual is often very small — and small numbers compress extremely well. WebP also supports variable-size transform blocks (4×4, 8×8, 16×16) letting the encoder use small blocks for high-detail areas and larger blocks for smooth gradients. The practical result: WebP files are typically 25–34% smaller than JPEG at equivalent visual quality.
How AVIF Goes Further
AVIF takes the same intra-frame prediction concept further with AV1's vastly more sophisticated toolset. AV1 supports transform blocks up to 64×64, over 50 directional and non-directional intra prediction modes, and a more efficient arithmetic entropy coder called ANS (Asymmetric Numeral Systems). AVIF also natively supports 10-bit and 12-bit colour depth, HDR imagery, and alpha transparency — features JPEG simply cannot handle. The combined effect is roughly 50% better compression than JPEG at equivalent visual quality, meaning an AVIF file that looks identical to a 200 KB JPEG can weigh as little as 100 KB. As of 2025, AVIF is supported by all major browsers including Chrome, Firefox, Safari, and Edge.
| Format | Year | Compression vs JPEG | Best Use Case |
|---|---|---|---|
| JPEG | 1992 | Baseline | Universal compatibility |
| WebP | 2010 | ~30% smaller | Web images, good browser support |
| AVIF | 2019 | ~50% smaller | Modern web, HDR, 10-bit colour |
7. WebAssembly — The Privacy Revolution in Browser Compression
For most of the internet's history, running professional-grade image compression in a web browser was impossible. JavaScript is simply too slow — a MozJPEG encode that a native C program completes in 50 milliseconds might take 5–10 seconds in JavaScript, making the experience unusable for large files. The solution arrived in 2017: WebAssembly (Wasm).
WebAssembly is a binary instruction format that allows C, C++, and Rust code to be compiled into a compact bytecode that browsers execute at near-native CPU speed. The key phrase is "near-native" — Wasm typically runs at 80–95% the speed of equivalent native machine code, compared to JavaScript which often runs at 10–20% of native speed for computation-heavy tasks. This performance leap is what makes client-side compression viable for production use.
CompressPic uses the exact same compression codecs that power professional desktop tools: MozJPEG (Mozilla's fork of libjpeg-turbo with improved quantization tables and trellis optimization) and libvips (a high-performance image processing library used by Cloudflare, Shopify, and Wikipedia). Both are written in C and compiled to WebAssembly using Emscripten, then run in multi-threaded Web Workers so they don't block the UI thread. The result is compression quality and output that is bit-for-bit identical to what a command-line tool would produce — but running entirely inside your browser, with zero network upload required.
- 100% Privacy: Your photos, passport scans, medical images, or confidential company graphics never leave your device. There are no server logs, no cloud storage, no retention policy to worry about.
- Zero Upload Latency: Because nothing is sent to a server, compression begins immediately. A 10 MB file compresses in about the same time on a satellite internet connection as on fibre.
- No File Size or Batch Limits: Server-based tools impose upload limits (often 5–20 MB per file) to control bandwidth costs. With local Wasm processing, you can compress 200 MB RAW exports or 50-image batches without any restriction.
8. Quality Settings — The Practical Guide
The quality slider is the single most impactful variable under your control. Contrary to popular belief, quality 100 does not mean "perfect" — it means "use the mildest possible quantization matrix." Even at quality 100, JPEG still applies chroma subsampling and DCT quantization; it just divides by very small numbers so almost nothing rounds to zero. Quality 1 means "divide by the largest possible numbers" — most frequency coefficients collapse to zero and the image becomes a pixelated, blocky mess.
| Quality | File Size vs Q95 | Visible Artefacts | Best For |
|---|---|---|---|
| 95 | Baseline | None visible | Print, archiving |
| 85 | ~40% smaller | Invisible at normal zoom | Product shots, text-heavy images |
| 75–82 ★ | ~65–75% smaller | Imperceptible at 1x zoom | Web photography, hero images |
| 65 | ~80% smaller | Slight banding in gradients | Thumbnails, background images |
| 50 | ~88% smaller | Visible blocking on edges | Tiny thumbnails only |
Content type matters enormously. A landscape photograph of rolling hills and a blue sky has very little high-frequency content — smooth gradients dominate — and can tolerate quality as low as 65–70% before banding becomes noticeable. A close-up portrait with fine hair detail, skin texture, and a sharp fabric pattern has a lot of high-frequency content and needs quality 75–82% to avoid blocking around hair strands. A product image with a white background and crisp logo text is the most demanding scenario — logos and text have extremely sharp, hard edges at high contrast, and JPEG ringing artefacts appear as halos around every letter. For that use case, consider using a PNG or WebP lossless mode for the logo overlay and JPEG only for the photographic product itself.
💡 Pro Tip — The Sweet Spot
The quality range 75–82 is considered the web photography "sweet spot" because it sits just above the perceptual threshold where JPEG blocking becomes visible on high-DPI Retina displays at 100% zoom. For WebP and AVIF, the equivalent sweet spot is approximately 72–80 due to their better high-frequency handling.
9. Common Compression Mistakes to Avoid
Knowing the theory matters, but the most practical lessons come from the mistakes that cost people quality, disk space, or both. Here are the five most common compression errors we see, and how to avoid them.
⚠️ Mistake 1: Re-compressing an Already-Compressed JPEG
Every time you save a JPEG that was itself already a JPEG, you apply a fresh round of quantization on top of the existing quantization artefacts. This is called generation loss, and it compounds with each iteration. After 3–4 re-saves at quality 75, you can see visible blocking and smearing that was not present in the original. Always keep your master file in a lossless format (PNG or TIFF) and generate the compressed JPEG from the master only once.
⚠️ Mistake 2: Using PNG for Photographs
PNG lossless compression on a photographic image typically yields files of 3–8 MB compared to a visually identical JPEG at 200–400 KB. That is a 10× to 20× size penalty for zero perceptual benefit in a photograph. PNG is the right tool for logos, UI screenshots, and diagrams with large flat-colour areas where lossless accuracy matters. Using it for photos is one of the most wasteful mistakes in web development.
⚠️ Mistake 3: Setting Quality Too Low for Faces and Text
Portrait photography and product images with fine text on labels are the most sensitive to compression artefacts. Human faces trigger pareidolia-like scrutiny — viewers are exquisitely attuned to subtle degradation in skin tone gradients, eye detail, and hair. Similarly, text in images (ingredient labels, book covers, menus) degrades visibly at quality below 80% due to JPEG ringing around the hard black-on-white edges. Treat these content types differently from landscape photography and use higher quality settings accordingly.
⚠️ Mistake 4: Not Stripping EXIF Metadata
Modern smartphone cameras embed EXIF metadata in every JPEG: GPS coordinates, camera model, lens details, date and time, shooting parameters, and sometimes a full-resolution thumbnail of the image itself. This metadata silently adds anywhere from 50 KB to 500 KB to your file size — sometimes more than 10% of the compressed image weight — without contributing a single pixel to the visible image. It also leaks precise location data. Always strip EXIF before publishing images to the web unless you specifically need it (as in photojournalism workflows with copyright data).
⚠️ Mistake 5: Compressing Your Master Archive Files
Your original camera RAW or high-quality TIFF/PNG masters should never be compressed with lossy settings and used as the new "original." Web images frequently need to be reprocessed for new formats (as AVIF becomes standard, you'll want to re-encode from the master), resized for different breakpoints, or cropped differently. If your master is already a lossy JPEG, every downstream operation inherits its artefacts. Store masters in their original formats, back them up immutably, and treat compressed web exports as disposable output.
Frequently Asked Questions
What is the difference between lossy and lossless compression?
Lossless compression reduces file size by identifying and eliminating statistical redundancy without altering any visual pixel data. When decompressed, the image is mathematically identical to the original — PNG is the classic example. Lossy compression goes further by permanently discarding subtle colour nuances that the human visual system cannot perceive, such as fine high-frequency texture variation in a blue sky. JPEG, WebP, and AVIF all use lossy techniques by default, achieving 65–90% file size reductions with near-imperceptible quality differences. For most web photography, lossy is the right choice; for logos, UI icons, or medical scans where pixel accuracy matters, lossless is mandatory.
How does JPEG compress images so effectively?
JPEG works through a four-stage pipeline that exploits human biology rather than just math. First, it converts RGB pixels to the YCbCr colour space, separating luminance (brightness) from chrominance (colour). Second, it applies 4:2:0 chroma subsampling — halving the colour resolution while preserving full brightness detail. Third, it divides the image into 8×8 pixel blocks and applies the Discrete Cosine Transform (DCT), converting spatial pixel values into frequency coefficients. Finally, a quantization matrix divides those frequency coefficients by progressively larger numbers, rounding many high-frequency values to zero, and the resulting sparse data is compressed losslessly with Huffman coding. The quality slider you set controls how aggressively the quantization matrix divides — lower quality means larger divisors and more zeroed-out coefficients.
Does compressing an image in the web browser compromise quality?
No — browser-based compression can be just as good as server-side tools. CompressPic executes the exact same C/C++ compression codecs (compiled to WebAssembly) used by professional desktop tools like MozJPEG and libvips. These codecs run at near-native CPU speed inside the browser sandbox, producing output that is bit-for-bit identical to what a command-line tool would generate. The key advantage is privacy: because everything runs locally on your device, your images never leave your machine, eliminating the upload latency and data-retention risks associated with cloud processing services.
What quality setting should I use for web images?
For most web photography displayed on standard Retina or high-DPI screens, a JPEG or WebP quality of 75–82% is the sweet spot — you achieve 70–80% file size savings with effectively zero visible difference at typical viewing distances. Portrait photography with fine facial detail can tolerate quality down to 72–78%, while images with smooth sky or water gradients can go as low as 65% before banding becomes noticeable. Text-heavy images, product shots with label detail, and logos compressed to JPEG need higher quality (85–92%) because lossy artefacts appear as ringing and blur along hard contrast edges. Use CompressPic's interactive split-screen slider to A/B compare at 100% zoom and find the ideal setting for your specific image.
Why is AVIF so much better than JPEG?
AVIF is based on the AV1 video codec's intra-frame encoding technology, which uses far more sophisticated prediction and transform coding than JPEG's 1992-era DCT algorithm. Instead of processing each 8×8 block in isolation, AVIF uses intra-frame prediction — each block is first predicted from its already-encoded neighbours, and only the residual (prediction error) is transform-coded. This dramatically reduces the amount of information that needs to be stored per block. AVIF also supports larger transform block sizes (up to 64×64), better chroma subsampling modes, and a more efficient entropy coder, collectively achieving roughly 50% better compression than JPEG at equivalent visual quality. As of 2025, all major browsers support AVIF natively, making it the best format for new web projects.
Can I compress an image multiple times without losing quality?
With lossless formats like PNG, yes — repeated compression and decompression introduces zero quality degradation because no pixel data is ever discarded. With lossy formats like JPEG, each re-compression cycle applies a fresh round of quantization on top of already-quantized data, compounding artefacts in a process called generation loss. After just two or three re-saves at quality 75%, you can begin to see ringing artefacts around high-contrast edges and posterisation in smooth gradients. The golden rule is: always keep your original uncompressed or losslessly-saved master file and generate the compressed web copy exactly once from that master. Never re-compress a JPEG to make a smaller JPEG.
Test Compression On Your Images Now
Upload any photo into CompressPic and use our interactive split-screen comparison slider to see the quality and file size difference in real time — no upload, no signup, 100% private.