Design faster web pages, part 1: Image compression

Lots of web developers want to achieve fast loading web pages. As more page views come from mobile devices, making websites look better on smaller screens using responsive design is just one side of the coin. Browser Calories can make the difference in loading times, which satisfies not just the user but search engines that rank on loading speed. This article series covers how to slim down your web pages with tools Fedora offers.

Preparation

Before you sart to slim down your web pages, you need to identify the core issues. For this, you can use Browserdiet. It’s a browser add-on available for Firefox, Opera and Chrome and other browsers. It analyzes the performance values of the actual open web page, so you know where to start slimming down.

Next you’ll need some pages to work on. The example screenshot shows a test of getfedora.org. At first it looks very simple and responsive.

Browser Diet - values of getfedora.org

Browser Diet – values of getfedora.org

However, BrowserDiet’s page analysis shows there are 1.8MB in files downloaded. Therefore, there’s some work to do!

Web optimization

There are over 281 KB of JavaScript files, 203 KB more in CSS files, and 1.2 MB in images. Start with the biggest issue — the images. The tool set you need for this is GIMP, ImageMagick, and optipng. You can easily install them using the following command:

sudo dnf install gimp imagemagick optipng

For example, take the following file which is 6.4 KB:

First, use the file command to get some basic information about this image:

$ file cinnamon.png
cinnamon.png: PNG image data, 60 x 60, 8-bit/color RGBA, non-interlaced

The image — which is only in grey and white — is saved in 8-bit/color RGBA mode. That’s not as efficient as it could be.

Start GIMP so you can set a more appropriate color mode. Open cinnamon.png in GIMP. Then go to Image>Mode and set it to greyscale. Export the image as PNG with compression factor 9. All other settings in the export dialog should be the default.

$ file cinnamon.png
cinnamon.png: PNG image data, 60 x 60, 8-bit gray+alpha, non-interlaced

The output shows the file’s now in 8bit gray+alpha mode. The file size has shrunk from 6.4 KB to 2.8 KB. That’s already only 43.75% of the original size. But there’s more you can do!

You can also use the ImageMagick tool identify to provide more information about the image.

$ identify cinnamon2.png
cinnamon.png PNG 60x60 60x60+0+0 8-bit Grayscale Gray 2831B 0.000u 0:00.000

This tells you the file is 2831 bytes. Jump back into GIMP, and export the file. In the export dialog disable the storing of the time stamp and the alpha channel color values to reduce this a little more. Now the file output shows:

$ identify cinnamon.png
cinnamon.png PNG 60x60 60x60+0+0 8-bit Grayscale Gray 2798B 0.000u 0:00.000

Next, use optipng to losslessly optimize your PNG images. There are other tools that do similar things, including advdef (which is part of advancecomp), pngquant and pngcrush.

Run optipng on your file. Note that this will replace your original:

$ optipng -o7 cinnamon.png 
** Processing: cinnamon.png
60x60 pixels, 2x8 bits/pixel, grayscale+alpha
Reducing image to 8 bits/pixel, grayscale
Input IDAT size = 2720 bytes
Input file size = 2812 bytes

Trying:
 zc = 9 zm = 8 zs = 0 f = 0 IDAT size = 1922
 zc = 9 zm = 8 zs = 1 f = 0 IDAT size = 1920
 
Selecting parameters:
 zc = 9 zm = 8 zs = 1 f = 0 IDAT size = 1920

Output IDAT size = 1920 bytes (800 bytes decrease)
Output file size = 2012 bytes (800 bytes = 28.45% decrease)

The option -o7 is the slowest to process, but provides the best end results. You’ve knocked 800 more bytes off the file size, which is now 2012 bytes.

To resize all of the PNGs in a directory, use this command:

$ optipng -o7 -dir=<directory> *.png

The option -dir lets you give a target directory for the output. If this option is not used, optipng would overwrite the original images.

Choosing the right file format

When it comes to pictures for the usage in the internet, you have the choice between:

JPG-LS and JPG 2000 are not widely used. Only a few digital cameras support these formats, so they can be ignored. aPNG is an animated PNG, and not widely used either.

You could save a few bytes more through changing the compression rate or choosing another file format. The first option you can’t do in GIMP, as it’s already using the highest compression rate. As there are no alpha channels in the picture, you can choose JPG as file format instead. For now use the default value of 90% quality — you could change it down to 85%, but then alias effects become visible. This saves a few bytes more:

$ identify cinnamon.jpg
cinnamon.jpg JPEG 60x60 60x60+0+0 8-bit sRGB 2676B 0.000u 0:00.000

Alone this conversion to the right color space and choosing JPG as file format brought down the file size from 23 KB to 12.3 KB, a reduction of nearly 50%.

PNG vs. JPG: quality and compression rate

So what about the rest of the images? This method would work for all the other pictures, except the Fedora “flavor” logos and the logos for the four foundations. Those are presented on a white background.

One of the main differences between PNG and JPG is that JPG has no alpha channel. Therefore it can’t handle transparency. If you rework these images by using a JPG on a white background, you can reduce the file size from 40.7 KB to 28.3 KB.

Now there are four more images you can rework: the backgrounds. For the grey background, set the mode to greyscale again. With this bigger picture, the savings also is bigger. It shrinks from 216.2 KB to 51.0 KB — it’s now barely 25% of its original size. All in all, you’ve shrunk 481.1 KB down to 191.5 KB — only 39.8% of the starting size.

Quality vs. Quantity

Another difference between PNG and JPG is the quality. PNG is a lossless compressed raster graphics format. But JPG loses size through compression, and thus affects quality. That doesn’t mean you shouldn’t use JPG, though. But you have to find a balance between file size and quality.

Achievement

This is the end of Part 1. After following the techniques described above, here are the results:

You brought image size down to 488.9 KB versus 1.2MB at the start. That’s only about a third of the size, just through optimizing with optipng. This page can probably be made to load faster still. On the scale from snail to hypersonic, it’s not reached racing car speed yet!

Finally you can check the results in Google Insights, for example:

In the Mobile area the page gathered 10 points on scoring, but is still in the Medium sector. It looks totally different for the Desktop, which has gone from 62/100 to 91/100 and went up to Good. As mentioned before, this test isn’t the be all and end all. Consider scores such as these to help you go in the right direction. Keep in mind you’re optimizing for the user experience, and not for a search engine.

For Developers Using Software

19 Comments

  1. Leandro Boari

    Good job!
    tinypng.com provides excellent compression as well.

    • true it does a good job but the difference to optipng and other featured tools, it doesnt work locally. So optipng I can script and automate it in my workflow. With tinypng I cant do that and need an internet connection and cause traffic

  2. TH301

    Excellent start on the series, hope the following will be just as detailed! Maybe dip into Static Site Generators like Hugo and certainly CSS Grid as it’s now well supported and finally makes it possible to make responsive easily maintained superminimalistic code without the help of CSS frameworks, hacks and other nuances that was a necessity of the past.

    Ruthlessly spamming some links to get headstarted…

    Can I use it? (Yes you can!):
    https://caniuse.com/#search=CSS%20Grid%20Layout

    Amazingly good talk by Rachel Andrew:
    https://www.youtube.com/watch?v=8ti7o-sQuYs

    Mozilla docs:
    https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

    25 videos by Wes Bos (all free!)
    https://cssgrid.io/

    Learn CSS Grid by Jonathan Suh:
    https://learncssgrid.com/

    The specs itself (yeah I know… partly written by Microsoft, but this is actually very good):
    https://www.w3.org/TR/css-grid-1/

    OK, I need to stop this linkspamming now! 🙂

    • no, we will not talk about CSS Grid and site frameworks like Hugo (But if you think thats something to talk about go ahead submit). Actually the title was changed by the editors, so “design” doesnt fit for what we do because we just make a “diet” on what we have, to save “calories” and speed up the loading time.
      If you look to the page which we using as example http://getfedora.org. You see, that the changes we did in this part not really make sense as there are better options for the pictures, so we will throw them away and use something what makes more sense… 😉

      • TH301

        Maybe not SSG, but I still think CSS Grid makes a lot of sense for taking getfedora.org on a diet and reducing its CSS calories, which is the highest % load in your screenshot. Getfedora.org are currently using the CSS framework Bootstrap. CSS Grid is kind of like a framework, but built directly into the browsers itself so you could get rid of Bootstrap altogether and more. Looking at the html source there’s a lot of div’s and bootstrap-classes that would no longer be needed as well and thereby reducing the overall load even further. It’s your series and I’m sure I will enjoy the read however it expands, but I do hope you will reconsider here.

        • I am sure the web team takes every help they can get

          • TH301

            I have to admit that when writing my first comment I thought the series was just just using getfedora.org to give some general advises and not actually be applied on getfedora.org. Applying grid would require a lot more work and testing so I totally understand why grid would be out of the scope for this series. That’s cool.

            Moving to grid however is still something I think would be beneficial for the future, so if I want to get my hands dirty (no promises), then were…
            1. Do I start a start a proper discussion with the web team?
            2. Do I submit patches against the website? Maybe there’s are a GitLab/Hub repo for this?

            I’m not familiar with how Fedora is organized so any direction would be helpful.

            PS: Also out of scope for this series, but when first speaking to a member I would strongly advice to get rid of all inline JavaScript and CSS so that CSP can be applied: https://infosec.mozilla.org/guidelines/web_security#content-security-policy
            And fedoramagazine.org is loading external JavaScript with no integrity check (SRI), that’s very easy and takes no time to apply: https://infosec.mozilla.org/guidelines/web_security#subresource-integrity

            Thanks for the improvements you make and all the best wishes for this series my friend. 🙂

  3. Martin

    Good to see this series!

  4. Great, I’ll start to apply it.

  5. Linux Creative

    My Tips for a ‘Site-Diet’ use “Save For Web” in GIMP for Graphics and ‘Ditch Bloated CSS/JavaScript Frameworks’ use custom CSS & Vanilla JS, modern browsers desktop/mobile has no problem with them. Also Dump all the Social Media and other Third-Party Junk Code slowing down sites. MSIE is Dead – It’s time to ‘Code Normal Again’ 8)

  6. D

    The advise here seems very outdated. Guetzli (near-lossless) and Zopfli (lossless) yields much better compression ratios for JPEG and PNG than traditional compactor tools. New image file formats like WebP yields even smaller files still and works with all major browsers (sans Firefox).

  7. Rene Reichenbach

    Its crucial to say that it mainly depends on the color count what format is the one to head for.

    rule of thumbs is:
    icons or graphics (low color count) png
    pictures or fotos (high color count) jpg

    and you could explain a bit more about vector graphics (svg)

    Besides this its a nice topic and i am looking forward to the next articles.

  8. Marcio

    Muito bom, o artigo é foi muito útil para melhor o desempenho do meu site, entretanto oi maior gargalo está por conta do JavaScript e o CSS!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat. Fedora Magazine aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. The Fedora logo is a trademark of Red Hat, Inc. Terms and Conditions

%d bloggers like this: