Techniques for Squeezing Images for All They’re Worth

An image’s dimensions on screen are measured in pixels: width and height.

An image’s quality is determined by less tangible factors: composition, mood, style, contents. But none of that matters if people get impatient waiting for the file to download.

Web images change in file size when compressed. Smaller files are faster to download, which makes for a better browsing experience.

But clear pictures make for a better experience, too. How much—and what kind of—compression should we apply? Are there alternatives to these messy trade-offs?

Here we look at some surprising facts about preparing image files for the web.

Making pages load fast is crucial to keeping the attention of visitors. They’re fickle folks these users, easily disappointed if they don’t get immediate results. When they click a link, they want the target right away.

One of the biggest bottlenecks on web pages is the size and quantity of images. The obvious solution is to use fewer images. But other techniques can help us get the most out of every pixel.

 

Pixels Are Information

The old cliché that a picture is worth a thousand words is true. Think of a pixel (short for “picture element”) as a unit of information.

More pixels mean more data, which affects both the viewing and resampling of an image. Just as more words can make a paragraph more descriptive, more pixels can make a picture more informative. (Of course, using the right words leads to a better paragraph, just as using the right pixels leads to a better image.)

diagram of how fewer pixels tell less of a story

Photo courtesy of Jan Busby.

Smaller images don’t merely take up less space—they tell less of a story. Above, the same image at three different sizes becomes progressively harder to “read.”

The largest photo clearly shows the model’s eyelashes, teeth and strands of hair. The mid-sized photo loses those details. How long are those lashes? Is she smiling? It’s hard to tell. The smallest photo still resembles a person, but only with some imagination. A picture of a human face at fewer than 400 pixels is usually unrecognizable.

Although small images are harder to see, their size isn’t always a problem. Simple icons with simple messages don’t need many pixels. Many pixels may be needed to show a person’s portrait: their expression, characteristics, clothing and background. But a thumbnail link to the next portrait in a series has only one thing to say.

The question is, what’s the fewest number of pixels required to communicate “Click this to see the next image”?

diagram showing how extra pixels are not needed

Above, each of the arrows communicates “Next.” Graphics A and B are both very legible and convey the same message, but graphic A uses four times as many pixels to say the same thing.

At the other end, graphic E isn’t an arrow so much as a gray and black blob. It doesn’t have enough pixels (i.e. enough information) to be a recognizable shape.

If graphics A and B use more pixels than necessary, and E fails to communicate, then graphics C and D have just enough pixels to suggest a right-pointing shape. Sixty-four pixels are just barely enough to create an arrow shape (or to play Space Invaders).

The goal in sizing an image, then, is to make it large enough in file size to tell a story and small enough to download quickly.

 

Finding the “Ideal” File Size

Many factors affect legibility (or the clarity of information expressed in pixels): contrast, subject matter, the photographer or artist’s experience, lighting, detail, background noise and available space on the page. These all determine how small or large an image should be.

diagram showing where quality and file size meet

In the end, choosing the right image size is a judgment call. But compression is more than a trade-off between image quality and file size. Understanding how various forms of compression work can affect how you prepare your images.

Technically, a digital image is a set of pixels arranged on a grid called a bitmap. In a straight uncompressed bitmap, each pixel has its own description: pixel #1 has a particular mix of red, green and blue; pixel #2 has a different mix; and so on.

Compression algorithms reconstitute a bitmap, using less information to describe the same number of pixels. Most images on the web belong to one of two compression types: JPG or LZW (Lempel-Ziv-Welch, named after its inventors).

 

LZW Addresses Both Image Quality and File Size

GIF and 8-bit PNG images use LZW compression to minimize file size. LZW groups identical colors in an image per row.

A file in this format has a precise list of every color in it. Rather than record the values of red, green and blue for each contiguous row of pixels, this color palette enables the file to call for “color #1.”

diagram demonstrating how LZW compression saves space

Above, LZW compression assigns a color to 15 pixels in a row. Without LZW compression, each pixel would need its own color information. Redundant information increases file size. But LZW is effective only when rows contain many consecutive identical colors.

diagram showing how to use LZW compression more efficiently

Above, the top group of pixels has many interruptions. The compression algorithm can’t go more than two or three pixels without having to create a new group of colors. Because each group must be recorded in the file, eight records are created in the GIF and PNG files.

The second group is much better: only four groups of concurrent colors means half as many records in a GIF or PNG file.

As a result, GIF compression works better horizontally than vertically. If you have the choice, make the details horizontal. This is even more important than overall dimension: a narrow image with horizontal stripes tends to compress better than a wide image with vertical stripes. With LZW compression, it’s the details that count.

diagram of how LZW compression handles two images with stripes

Above, saving in GIF makes a big difference when the image is turned 90°: horizontal stripes require only 16% of the bytes required by vertical stripes.

LZW is said to be “lossless” because the format itself doesn’t alter the image. JPG is different.

 

JPG Clumps Complicated Details

JPG works best for live photographs, as it was designed to. This compression scheme clumps pixels into groups of around 8×8 by mixing their colors slightly.

More compression means that the pixels in a 64-pixel clump will become more similar. Then JPG tries to relate four groups of 8×8 pixels to each other. Then it groups those groups into another 2×2, and so on. This technique is called “lossy” compression because it introduces changes to the file.

The changes that JPG compression introduces to images are called artifacts. Naturally, more artifacts make for better compression but poorer image quality.

illustration of JPG artifacts mucking up a decent landscape photo

Above, a JPG saved at 0%, or full compression, makes its clumpy artifacts obvious. Hard edges and sharp contrast are JPG’s first signs. For example, the edge of the mountain against the cloud loses focus, and the right-hand shadow “jumps” to the edge of the nearest convenient 8×8 clump.

Fortunately, most photos retain enough information to minimize the problem. People are good at recognizing shapes, even if the shapes are slightly distorted.

 

Photoshop’s 19% trick

Here’s a tip for Photoshop users: Photoshop’s “Save for Web” feature has two parts that suddenly change the compression. Image → Save for Web lets you choose the amount of compression as a percentage: 0% is the lowest file size, 100% the highest. The difference between quality and file size becomes more pronounced between 19 and 20%.

infographic that shows how Photoshop compresses more below 19%

Notice the sudden drop in file size in the above illustration. If image quality is less important to you than downloading time, then compressing no higher than 19% will achieve the best quality for the lowest size. But if image quality is more important, then saving a JPG at no lower than 20% achieves the lowest size for the best quality. You’ll find a similar point at around 30 to 32%, though less drastic.

The differences in this 100×100 image are only a few bytes. But the savings add up, especially in larger photos.

 

CSS Sprites

Being files, all images on a web page must be requested from the server. Those requests give the server extra work to do. If you have many small images—icons, for example—that have a similar color palette, then CSS sprites can improve loading time.

A CSS sprite is a single file that holds many images within it. Using the width, height and background-position properties in CSS, you can make slices of the file appear in divs, links and other HTML elements. So, a single file fulfills multiple roles on the page. The advantage? Only one file to download. The disadvantage? It requires a little planning.

Add something here

Confirmed

Cancel

Sorry, access denied

Next page

Edit a photo

Power up

Green tag


The icons above (and the ones in this sentence) come from only one file: CSS sprite example. CSS will put an image and its dimensions in a , but each element must be repositioned to fit. Using the :hover pseudo-selector makes the math worth the effort, because sprites can enhance links and other elements on mouse-over. Try it below:

Icon 1

Icon 2

Icon 3

Icon 4


As you can see, the same image provides two states for the four icons. The only trick is in preparing the graphic file in advance and figuring out each icon’s coordinates.

sample CSS sprite with eight icons

(“Silk” icons courtesy of FamFamFam.)

As of this writing, both Yahoo! and Amazon use sprites for their frequently downloaded navigation labels.

 

Choosing the Right File Size

Not every pixel in an image is critical, but a designer’s neglect of file size often increases with the number of images on the page.

An image that could be 5% smaller isn’t a worry. Two images aren’t much more of a worry. But what about five images? Ten? At what point should the designer begin to worry about image compression? Everyone has a different threshold. Some don’t care at all.

Worrying is hard to do when a few extra kilobytes have no consequences. But ignoring compression becomes a gradually more serious problem that slows down websites and drives away visitors in the long run.


Written exclusively for Webdesigner Depot by Ben Gremillion. Ben is a freelance web designer who solves communication problems with better design.

What techniques do you use to get the most from your web images? How likely are you to spend time shaving off extra bytes? Share your thoughts in the comments below.

0 shares
  • http://qlassik.com Chris Hale

    Really useful, thanks

  • http://www.designcrumbs.com Jake

    Great post. I love using image sprites as much as possible. It always ‘irks’ me when I rollover something on a site and it takes 2 seconds for the rollover image to download and take affect when they could have easily used a sprite.

  • http://www.skix.pl SkiX

    Very interesting article! THX

  • http://desaindigital.com jeprie

    interesting article. Usually, I use save for web using setting JPEG high.

  • http://www.andMark.co.uk &Mark

    Very informative article – the 19% Photoshop rule is very useful tip – thanks!

  • http://www.loveishs.com/ tanya

    Thnx for sharing this useful article :)

  • http://stylishwebdesigner.com/ Stylish Web Designer

    I must say its a very useful article for designers. Thnx mate for sharing this

  • Mark

    Interesting to read this, I sometimes feel a bit of a lone champion of compression vs. quality. My general rules of thumb I’d add are…

    Use GIFs for anything graphical, especially with small palettes and JPEGs for anything photographic.

    Where you have both (e.g. text over photograph) I’d use a JPEG and find that 51% is the magic number that stops ugly artifacts around the text. Interestingly if you are overlaying white or black text on the photograph you can get away with a lower quality %.

  • http://balgle.designerteam.info Beth McLain

    Great solid information! Everyone should read this article.
    Keep up the good work.

  • http://look4jih.blogspot.com/ Jonathon Ingram Haigler

    .niiiiice breakdown m8.

  • http://www.jennamolby.com Jenna Molby

    Great article, thank you.

  • http://www.techpaf.fr Antoine

    Thanks for giving us this useful post
    Nice work ;)

  • http://sexidesign.com Melody

    Very true, it’s interesting how much is lost with pixelation. I see this a lot because of digitally painting portraits and needing a really high quality original photo, otherwise crucial details get lost in a bunch of confusing boxes..

  • http://aext.net Lam Nguyen

    Great and true! I really didn’t care at all about the compression. In addition, the non-well compressed image will slow down your website, also will kill your CPU usage in your hosting account.

    Very explained article, and I appreciate for such detail information the author gave here. Well done,

  • Rob

    Why even bother mentioning GIF? There is absolutely no reason to use that format. 8-bit PNG has been supported in every major browser since 1997.

    NINETEEN NINETY SEVEN!

    • Russ

      Maybe because 8-bit PNG doesn’t support animation.

      Read up more.. it’s 2010.

      TWO THOUSAND AND TEN

      • Rob

        Fine, one minor exception.

      • http://www.jc-designs.net/blog Jeremy Carlson

        I also thought only Fireworks supported PNG-8 with Alpha Transparency. I am pretty sure Photoshop does not yet. And yes I have to support IE6 still.

      • Rob

        Don’t confuse 8-bit PNGs with 8-bit+alpha PNGs. The latter contains an additional 8 bits of transperency data and doesn’t work in IE 6. The former only supports setting a single palette color as transparent (exactly like GIF) and works anywhere GIF does.

        There’s a LOT of misinformation out there about PNG.

    • http://benthinkin.net Ben Gremillion

      I included GIF because many developers and designers I’ve worked with prefer it when faced with PNG’s color shift problem. Others use it out of habit, or because they’re required to support IE6 and didn’t know the difference between PNG-8 and -24. On rare occasions I’ve seen GIF compress better than PNG. But professional or not, people use it.

      Good point about zlib — mistake on my part.

      • Rob

        If by “PNG’s color shift problem” you mean “Adobe CS2’s PNG color shift problem”, there’s been a number of simple solutions for that from the start. The easiest is simply to run the files through an application like ImageOptim or PNGcrush, which strips the unnecessary and incorrect gamma data.

        Regardless of that bug, this is a good step to take anyway since it results in significantly smaller files. The only time I have ever seen a properly compressed GIF have a smaller file size than a properly compressed PNG is with extremely small files (<.5k).

        If you want I'd be glad to share some of my tips for squeezing every bit out of PNGs.

      • http://benthinkin.net Ben Gremillion

        Please do. The more ideas and techniques we share, the better for the community.

  • Rob

    Also, PNG uses DEFLATE (zlib), not LZW.

  • http://www.bebop-ad.com BebopDesigner

    This is a bible! Thanks for such valuable piece of advice. Excellent post

    cheers

  • http://3circlestudio.com/ Justin Carroll

    Pro, informative and good on ya for calling out the PS trick.

  • http://www.orphicpixel.com Mars

    this is a great article full of information

  • Bhargav

    This is really useful article. Nicely arranged and explained.
    Thanks & appreciated for sharing it.

  • http://www.webdesigner-michigan.com Kevin Mist

    This subject is a touchy one.. it is walking the tight-rope between quick and good looking. I spend a whole lot of time tweaking as many pixels out of images to make things run as quick as possible yet retaining a good look.

  • http://warstwy.com adone

    Next amazing article. Thanks

  • http://www.dharne.com/website_design.php Jane Cooke

    An absolute must read for any web designer. This is the easiest way I have seen LZW and JPG compression explained so far in terms of how it affects an image.

  • http://sideradesign.com paul

    I usually save JPGs between 60-70%, then I use smushit. I install the smushit plugin on all my WP sites too.

  • Fran

    I’ve found that you can push regular images (photographs) with a lot of detail down to about 45% before you start seeing significant (noticeable) jpeg artefacts. Sharp text or lines tend to create more artefacts.

    Progressive jpegs are also great since te image can finish loading at low quality as it progressively increases the quality. This way you’ll skip the open white blocks. Progressive files also tend to be 1 or 2 KB smaller for large files.

  • http://dannyhouk.com Danny

    Ben, hands down best image compression article I’ve read. This is a topic near and dear to me since I create elearning courses for low to medium range bandwidth, so I, like you, try to push every pixel’s compression.

    I was starting to write up an article like this for my blog… so may quote from this article (with credit) if any of the concepts make it over. For more depth, I would have also been interested to see a comparison of transparency channels with GIF and PNG (and alpha transparency with PNG 24). Though I know that’s beyond the scope of what most users need to know.

    Anywho, awesome job!

  • http://www.alejandroperazzo.com Punta del Este Real Estate

    great article, i usually save for web with medium quality.

    hey how about a newsletters article!!!!!!!! dont know why there is no information about making newsletters online, guess that designers dont want to share that. i had to learn all by my self. and i really love to have something to compare.

  • http://www.merman.us Merlin

    Can you define parts of a jpeg with different compression qualities? For example a persons face would retain high quality while the backdrop is low-quality & thus lower file size? I would think software specializing in exporting jpegs could do this.

    • http://benthinkin.net Ben Gremillion

      If it’s possible, I haven’t seen it. A jpg image has one compression setting for the entire file.

      The closest technique might be to slice the original image into different files, each with its own compression (or even its own file format). Adobe ImageReady has a good range of options with its slice tool.

      Another idea: Try blurring the background slightly. As areas with hard edges tend to compress better, regions with less detail should help a jpg’s overall file size.

    • Rob

      Unfortunately, that isn’t part of the JPEG spec. Some programs have figured out how to bend the rules, but I wouldn’t recommend using it since you’d be generating corrupted images, so you might get bad results.

      One of the new features of JPEG2000 is exactly what you’re looking for. They call it “Random code-stream access and processing” (http://www.computer.org/portal/web/csdl/doi/10.1109/DSD.2004.1333281). Photoshop CS3 and CS4 do a great job supporting this new feature, but you need to install the JPEG2000 plugin from the Goodies folder on the installer DVD.

    • Rob

      I forgot to mention that JPEG2000 has almost no browser support.

  • http://www.aledesign.it aledesign.it

    Nice article..so useful. Thanks