Categories
Internet

How to optimize images and improve website performance

Why do you need to optimize images and improve website performance at all in today’s 4G world?

Images constitute a huge chunk of all the data that is loaded when you visit a webpage. I am not even talking about photo blogs. From news aggregators to shopping portals, from Government websites to brochures – images are everywhere. The problem is that the images take up a lot of space. And transferring this large chunk of data takes time. God forbid, if your website takes more than 3 seconds, 90% of the users are likely to just jump elsewhere.

Recommended Reading – What are bounce rates and how do you reduce them?

There are plenty of options that are available to you today though. From the age old and trusty JPEG standards to today’s shiny new SVGs – you can optimize images the way you want – finding a balance between quality and performance that best suits your needs.

optimize images and improve website performance

There is one important point that I must emphasise – there is no one size fits all here. This of course can’t be applied when you are automating the process of optimization. But image compression and optimization is subjective. But more on that later.

Essential Reading – Optimizing images for web content

Image loading – how much do images affect typical websites?

Let’s take the top ten websites that human beings load all over the world. Then we can get the ratio of size of images combined to their total payload. Let’s assume they are using only raster images – I am not going to count SVG or CSS3 images here. I will visit them separately.

There are different image types that you can choose from. It depends on the type of website you are building.

To put it simply, these are the general guidelines that are usually followed (and that make sense)

  • Regular images for any generic website – JPG
  • Photographs or Portfolio type of images – PNG
  • Animations – Try your best to avoid using GIFs. Try emulating the same effect using CSS3 animations. If all else fails, then go for GIFs.
  • Icons – PNG files are good. You may also look for CSS3 icons, of even use SVG. Avoiding PNG will help you keep even the images scalable without losing information.

Of course, the designer’s job will end right at choosing how things look in a website. A frontend developer will have to weigh in the pros and cons of one file type or another to acheive the same graceful experience for the end user.

Different image file types and their ‘costs’

While PNG files take up more space than JPG for a similarly sized image – the other alternatives are not so simple. But even then, the below table still holds true for the majority of the conditions.

File type File size When to use
JPEG Smallest All general images, except those mentioned below
PNG Medium – Large Product or portfolio, icons, images with important detail
SVG Small to medium Icons, illustrations, graphs or anything that you need to scale indefinitely without losing quality
GIF Small to medium Animated icons, small animations

However, things are not so simple. They never are.

Take for instance, the JPEG files. Let’s take a sample image for instance and tweak its quality setting to note how good it looks and what size it comes down to.

Compressing JPEG files

If you wish to test it, you can use any of the apps that do it currently. GIMP, Photoshop and many other support this as well. For those who do not wish to download any application or are okay with simplicity, check this site out.

jpeg - optimize jpeg images and improve performance
This jpeg image weighs about 115 KB. Try different compression settings using the tool above and compare the quality

The original file weighs 115.9 KB. After processing with a 60% quality filter I get a file that weighs 82.2 KB.

For a particular resolution, that is all that I can ask for. In fact if I want to use the image in a website, I will most likely use it at a resolution of 640 pixels by 360 pixels. Resizing it further reduces the size to a ridiculous 13.6 KB. I can easily hyperlink this image to my original image for those who wish to download it.

optimized image - jpeg format compress images and improve website performance
Check how quickly and easily the image size shrunk

For my page load, this is sufficient. With JPEG, it is this easy to save bandwidth. For editing images in bulk, you can use IrfanView for batch compression.

jpeg quality vs size graph (Source: Wikipedia) compress images and improve website performance
As can be seen, going above 80% in terms of quality leads to a rapid growth in size. I prefer to keep it around 75%. That is my sweet spot.

The quality vs size graph shows what benefit to cost you can incur.

Compressing PNG files

For PNG files, things becomes tricky. Using the above website for compression will yield funny results. Since PNG needs to be compressed losslessly – you may end up with ‘compressed’ files that are much larger in size than their previous equivalents.

This is almost always not an issue with the image but with the algorithm being used. While there are the regular applications (read GIMP and Photoshop) that can do the same, online tools for compressing PNG files are fewer.

I prefer Tiny PNG for getting this done. Though there are no settings you can tweak it gets the job done. I was easily able to compress a PNG image from 61.6 KB to 19.3 KB. Impressive!

tinypng PNG compress images and improve website performance

If you are not interested in changing your JPEG compression settings, tinypng can actually compress JPEG for you too.

Compressing SVG and CSS

SVG files are not raster images. These are XML based vector images that rely on drawing images based on coordinates rather than pixels. So pixelation is not an issue. The biggest advantage is that vector images will not look ‘blurry’ even if they are magnified by a hundred or more times. This does not even come at the cost of image size.

A simple way to explain SVG would be this.

Imagine a triangle with three points or coordinates marking vertices. Straight lines connect the three and the inner void or background is deep blue in color.

raster PNG image of a blue triangle
This is a raster image. Look how blurry this looks!

A raster image will populate the whole image in pixels. But pixels are bound by their native resolutions. Once you magnify them, the observed resolution may (and will) be more than it’s native one. Now suppose you magnify an image of 400 X 300 pixels to 800 X 600 pixels. The smaller image does not have as much data as the larger image.

So how does it expand the image and display the same to you?

It follows a crude method – simply by averaging consecutive data points and filling the one that lay in between. This creates a blurred look.

The native resolution of the above image is 207×139 pixels. Look how it looks magnified.

The SVG triangle will act differently. No matter how much you magnify the image, the basic design of the image remains the same because the coordinates remain the same. Even the background color remains the same.

Interested in what this does below? Fire up a text editor and paste the code below. Then save it as <anything>.svg. Then double click to open the file. 🙂

<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="210mm" height="297mm" viewBox="0 0 210 297" version="1.1" id="svg8" inkscape:version="0.92.3 (2405546, 2018-03-11)" sodipodi:docname="triangle.svg">
  <defs id="defs2"></defs>
  <sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.35" inkscape:cx="-82.857143" inkscape:cy="560" inkscape:document-units="mm" inkscape:current-layer="layer1" showgrid="false" inkscape:window-width="600" inkscape:window-height="400" inkscape:window-x="0" inkscape:window-y="27" inkscape:window-maximized="1"></sodipodi:namedview>
  <metadata id="metadata5">
    <rdf:rdf>
      <cc:work rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"></dc:type>
        <dc:title></dc:title>
      </cc:work>
    </rdf:rdf>
  </metadata>
  <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1">
    <path style="fill:#0000ff;stroke:#000000;stroke-width:0.43861213px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="M 81.344784,45.399954 -3.6163237,191.07543 212.97468,176.63911 Z" id="path815" inkscape:connector-curvature="0" inkscape:export-xdpi="24.197599" inkscape:export-ydpi="24.197599"></path>
  </g>
</svg>

A simple look at the SVG file contents will clear it up. Open the svg image using any text editor.

For this triangle image this is what I see.

SVG XML content - optimize images to improve website performance
Any text editor will show you the data within. You can edit these too. The image will also obviously change.

Ignore the metadata and everything at the top. Look at the information enclosed in the <path> tag. That is pretty much all that the file defines.

And you are correct – removing most of the previous information will still make it work. You get to reduce it’s size even further.

Let’s take a more complicated vector image and check it’s size for raster equivalents.

The GNU goat head image in JPEG format - optimize images to improve website performance
GNU goat head in JPEG format
The same image in PNG format
The same image in PNG format. This weighs more but does not look any different (almost) to the human eye at native resolution

This simple GNU goat head image is in PNG format. The original SVG is here.

Check the below size comparisons.

PNG 85 KB
JPG 34 KB
SVG 24 KB

It’s pure SVG above. Magnify as much as you wish to.

SVG is pretty cool, right?

Better. Remember what I told you about removing the metadata that took up space and SVG being an XML based format?

That means they can be further compressed/minified/gzipped to SVGz formats that are supported by all major browsers natively.

For smart minification, you need to look no further than Jake’s tool at github.

For GIF, the GIM Compressor does a good job.

So why not use SVG for everything?

Well, small images are better off as PNGs or even JPEGs. Small icons and the like can size up almost similar. It is at greater resolutions that the size becomes an issue.

The major area where SVG excels however is images with a certain geometric pattern. Natural images are horribly produced in SVG.

Try converting the first beach image to SVG.

Here, let me try using this application.

Yuck!

But this is not surprising. I have not included the SVG version of it. I suggest you try other images that are ones that you take with your camera. More often than not, the images will turn out horrible.

Then try converting images that are more ‘digital’ in nature. Lego blocks for instance, or boxes and you will get a more proper image. But even then their size will be enormous because – COUNT THE EDGES!

Natural images have more natural paths. More natural paths equal more vertices and coordinates to store. This results in a complex image that is not worth the effort of vectorification. You are better off with JPEG or even JPEG 2000 in that case.

The curious case of Image Sprites

Image sprites became popular in the past decade. Rather by the end of it. In theory it sounded great and worked wonders. It reduced round trip times and hit servers less.

Things changed when the SVG or CSS icons came in. Or when relying on the local cache became more important.

Even today the beautiful post from CSS Tricks ranks up there promoting CSS sprites. The worrying thing is that it was written way back in 2009. That is about 10 years back!

Should you avoid them?

Probably not. They can help.

But do go through this post and use them sparingly and judiciously.

To optimize images and improve website performance I don’t recommend using image sprites any longer. Icons are better off as smaller PNGs. Use Font based icons instead if you have to.

Conclusion

So a method of mix and match suits best. Generally go for JPEG images. Tweak the quality where you need fine tuning. For smaller icons go with PNGs and for graphs and the like – SVGs look good.

By Sarthak Ganguly

A programming aficionado, Sarthak spends most of his time programming or computing. He has been programming since his sixth grade. Now he has two websites in his name and is busy writing two books. Apart from programming, he likes reading books, hanging out with friends, watching movies and planning wartime strategies.

Leave a Reply

Your email address will not be published. Required fields are marked *