When people talk about image optimization, they consider only the limited parameters offered by popular image editors, like the “Quality” slider, the number of colors in the palette, dithering and so on. Also, a few utilities, such as OptiPNG1 and jpegtran2, manage to squeeze extra bytes out of image files. All of these are pretty well-known tools that provide Web developers and designers with straightforward techniques of image optimization.

In this article, we’ll show you a different approach to image optimization, based on how image data is stored in different formats. Let’s start with the JPEG format and a simple technique called the eight-pixel grid.

Eight-Pixel Grid

As you already know, a JPEG image consists of a series of 8×8 pixel blocks, which can be especially visible if you set the JPEG “Quality” parameter too low. How does this help us with image optimization? Consider the following example:

32×32 pixels, Quality: 10 (in Photoshop), 396 bytes.

Both white squares are the same size: 8×8 pixels. Although the Quality is set low, the lower-right corner looks fuzzy (as you might expect) and the upper-left corner looks nice and clean. How did that happen? To answer this, we need to look at this image under a grid:

As you can see, the upper-left square is aligned into an eight-pixel grid, which ensures that the square looks sharp.

When saved, the image is divided into blocks of 8×8 pixels, and each block is optimized independently. Because the lower-right square does not match the grid cell, the optimizer looks for color indexes averaged between black and white (in JPEG, each 8×8 block is encoded as a sine wave). This explains the fuzz. Many advanced utilities for JPEG optimization have this feature, which is called selective optimization and results in co-efficients of different quality in different image regions and more saved bytes.

This technique is especially useful for saving rectangular objects. Let’s see how it works with a more practical image:

13.51 KB.

12.65 KB.

In the first example, the microwave oven is randomly positioned. Before saving the second file, we align the image with the eight-pixel grid. Quality settings are the same for both: 55. Let’s take a closer look (the red lines mark the grid):

As you can see, we’ve saved 1 KB of image data simply by positioning the image correctly. Also, we made the image a little “cleaner,” too.

Color Optimization

This technique is rather complicated and works only for certain kinds of images. But we’ll go over it anyway, if only to learn the theory.

First, we need to know which color model is being used for the JPEG format. Most image formats are in the RGB color model, but JPEG can also be in YCbCr, which is widely used for television.

YCbCr is similar to the HSV model in the sense that YCbCr and HSV both separate lightness for which human visual system is very sensitive from chroma (HSV should be familiar to most designers). It has three components: hue, saturation and value. The most important one for our purposes here is value, also known as lightness (optimizers tend to compress color channels but keep the value as high as possible because the human is most sensitive to it). Photoshop has a Lab color mode, which helps us better prepare the image for compression using the JPEG optimizer.

Let’s stick with the microwave oven as our example. There is a fine net over the door, which is a perfect sample for our color optimization. After a simple compression, at a Quality of 55, the file weighs 64.39 KB.

Open the larger version of the image in Photoshop, and turn on Lab Color mode: Image >> Mode >> Lab Color.

Lab mode is almost, but not quite, the same as HSV and YCbCr. The lightness channel contains information about the image’s lightness. The A channel shows how much red or green there is. And the B channel handles blue and yellow. Despite these differences, this mode allows us to get rid of redundant color information.

Switch to the Channels palette and look at the A and B channels. We can clearly see the texture of the net, and there seems to be three blocks of differing intensities of lightness.

We are going to be making some color changes, so keeping an original copy open in a separate window will probably help. Our goal is to smooth the grainy texture in these sections in both color channels. This will give the optimizer much simpler data to work with. You may be wondering why we are optimizing this particular area of the image (the oven door window). Simple: this area is made up of alternating black and orange pixels. Black is zero lightness, and this information is stored in the lightness channel. So, if we make this area completely orange in the color channels, we won’t lose anything because the lightness channel will determine which pixels should be dark, and the difference between fully black and dark orange will not be noticeable on such a texture.

Switch to the A channel, select each block separately and apply a Median filter (Filter >> Noise >> Median). The radius should be as small as possible (i.e. until the texture disappears) so as not to distort the glare too much. Aim for 4 in the first block, 2 in the second and 4 in the third. At this point, the door will look like this:

The saturation is low, so we’ll need to fix this. To see all color changes instantly, duplicate the currently active window: Window >> Arrange >> New Window. In the new window, click on the Lab channel to see the image. As a result, your working space should look like this:

The original is on the right, the duplicate on the left and the workplace at the bottom.

Select all three blocks in the A channel in the workplace, and call up the Levels window (Ctrl+L or Image >> Adjustments >> Levels). Move the middle slider to the left so that the color of the oven’s inside in the duplicate copy matches that of the original (I got a value of 1.08 for the middle slider). Do the same with the B channel and see how it looks:

As you can see, we removed 5 KB from the image (it was 64.39 KB). Although the description of this technique looks big and scary, it only takes about a minute to perform: switch to the Lab color model, select different regions of color channels and use the Median filter on them, then do some saturation correction. As mentioned, this technique is more useful for the theory behind it, but I use it to fine-tune large advertising images that have to look clean and sharp.

Common JPEG Optimization Tips

We’ll finish here by offering some useful optimization tips.

Every time you select the image compression quality, be deliberate in your choice of the program you use for optimization. JPEG standards are strict: they only determine how an image is transformed when reduced file size. But the developer decides what exactly the optimizer does.

For example, some marketers promote their software as offering the best optimization, allowing you to save files at a small size with high Quality settings, while portraying Photoshop as making files twice as heavy. Do not get taken in. Each program has its own Quality scale, and various values determine additional optimization algorithms.

The only criterion by which to compare optimization performance is the quality to size ratio. If you save an image with a 55 to 60 Quality in Photoshop, it will look like and have the same size as files made with other software at, say, 80 Quality.

Never save images at 100 quality. This is not the highest possible quality, but rather only a mathematical optimization limit. You will end up with an unreasonably heavy file. Saving an image with a Quality of 95 is more than enough to prevent loss.

Keep in mind that when you set the Quality to under 50 in Photoshop, it runs an additional optimization algorithm called color down-sampling, which averages out the color in the neighboring eight-pixel blocks:

48×48 pixels, Quality: 50 (in Photoshop), 530 bytes.

48×48 pixels, Quality: 51 (in Photoshop), 484 bytes.

So, if the image has small, high-contrast details in the image, setting the Quality to at least 51 in Photoshop is better.

Reinis Lejnieks

Paul d'Aoust

The need to shave 100 b off a file may pale in the days of ‘unlimited’ storage and fat pipes, but I also think that the craft is just as important as the art. It’s about taking pride in creating a thoroughly high-quality piece of work.

I remember reading about assembly-language programmers working on microcontrollers, who would rewrite chunks of code to save three or four bytes. Now that’s craft!

I really enjoyed this article; it’s a good bit of info to put into my quiver.

One question: Are you running Photoshop on Linux in the last screenshot?!

0

405

George

@Paul: there’s still the issue of a web server having to store and process a ton of images in RAM (assuming a CDN isn’t being used) which can be made easier if it’s processing a large number of images that are of a smaller file size.

Philip

Looking forward to PNG. Be sure to include those juicy gAMA chunks! This is what I came across: I saved a PNG for web out of Illustrator (I’m working on XP, unfortunately without Fireworks…). Of course, of all browsers it was only Explorer 8 that displayed that PNG file with a darker background (i.e. not matching my background color set in CSS). Weird. So I googled “IE8 shows different colors png” and lo and behold, Illustrator and Photoshop save PNGs with gAMA chunks – responsible for the darker color value! Jeez… TweakPNG helped me out. I miss my Fireworks – for web work it really has many advantages compared to PS and Illustrator (e.g. saving Alpha PNGs, creating mock ups in due time, etc.).

0

1112

gevv

Simon Day

I have worked for a few very large companies and in all of them we have had debates on how to shave the most possible from the page. It saves the company server costs and allows even the slowest connections a quicker load time.

When your site is generating millions in revenue and has millions of page impressions a day even a few bytes can save thousands!

Luis Lopez

Greg

“@greg: I think the issue here is workflow and considering the merits of spending a minute per image on a process that has a relatively limited payoff.

Being a professional includes making sure that one is working to schedule and using allocated hours wisely. It’s to do with simple economics (not ethics).”

You’ve completely missed my point. If you’re wasting too much time optimizing images, then you have other issues. And as a designer, work ethic is probably my top concern. It encompasses quality, practice, AND economics… all of which end up in a product that delivers on all fronts.

Dismissing something like a “few bytes” is NOT good work ethic, and ignoring that fact or not spending a little extra time to possibly save thousands is not wise at all.

Knee Grow

Conrad Chu

Re: Shir Gans comment on PNG-24 being less heavier than JPG when the image contains a lot of white spaces… FYI, punypng takes that into consideration when it processes JPGs. Sometimes it comes back with a png, sometimes as JPG. punypng just takes both routes and see which ones works better.

0

2223

Alvaro

I didn’t know about the difference between quality 50 and 51 in Photoshop. In other programs you control quality (quantization) and chroma-sumbampling separately. That is very important: subsampling (e.g. YUV 4:2:0) works well and is not noticed in photographs, but degrades quality a lot in drawings with saturated colors.

Apart from Photoshop’s Save for Web I recommend RIOT for quick saving of JPEG/PNG (or its Irfanview plugin). You can change quality settings interactively, switch between JPEG and PNG, reduce number of colors, etc. and see the final result live.

0

2324

KristinCurrier

Hmm. As someone who does mainly retouching for web product photography, this is pretty interesting. I’m always on the lookout for methods that make a product look as good if not better than it does in reality. The info on the 8px grid is very beneficial, and explains a lot. I have to take a lot of large silo’d product images and produce many smaller collateral versions of them, and they get fuzzier the smaller they get, regardless of optimization quality readings. My goal is to have a neat small image with a crisp white background. I will try using this grid.

One thing I do to prevent pixel “bleeding”…since I do major clipping paths on these product images already, I save the path, activate it, inverse it and delete the background around the silo image every time it is reduced in size. This does a fine job getting rid of artifacts and keeps lines very clean.

Also – some product images I do – luxury pens, for example – need to be shown both in a -45 degree angle, and horizontal. Changing a -45 degree angle pen image to horizontal results in jagged bitmapped images. Therefore, I process the incoming vertical photography and save out two master versions, one at a straight angle (vertical or horizontal) and another at -45 degrees that will never be used for anything but.

Good info on the LAB color. This will require more study for sure.

1

2425

Rochi

woneal

To those who are bickering about 1kb here, 1kb there, try working on banners that have a 40kb, or worse, 30kb ceiling. And there are six images in the banner. And there’s overhead for the animation and/or code for the interaction.

Many of you, it seems, haven’t worked in the “real world” where conditions aren’t dependent on YOUR wants and desires and abilities, but on the capabilities of the system, the inhibitions of particular serving platforms, and of course, the clients’ wants, that the files have to go through. It is a very rare day that one can create, produce, and deliver in a Utopian environment.

I have sometimes spent a whole day squeezing 2kb out of every item in a banner just to come under those specs.

Awesome insight into how the algorithms work – it’s helped me understand a lot better how I can even effect the originals in order to produce a smaller end result!

Thanks!

5

2627

Sergio Zambrano

You forgot to mention what are the MAIN factors for image compression, not size, resolution, nor colors, but any fine detail like graininess, sharpness and patterns.
Here I posted a short explanation of what matters when it comes to jpg compression, which also works for wordpress users, and gives you a few tips for really lower your bandwith: http://seosumo.com/right-compression-settings-to-save-jpg-images-for-wordpress

Hiren Khambhayta

Subscribe to our email newsletter for useful tips and valuable resources, sent out every second Tuesday.

It's finally here. Smashing Book #5, our new book on real-life responsive design. With front-end techniques and patterns from actual projects, it's a playbook to master all the tricky facets and hurdles of responsive design. Get the book.Free shipping.

Fixing RWD issues can be quite easy — once you understand exactly why they come up. The Mobile Web Handbook will help you understand technical issues on mobile and how to deal with them effectively.

Hungry for more content? Over 60 eBooks are waiting to be discovered in our lovely Smashing Library. And guess what? You can watch Smashing Conference talks there, too.