Optimizing Images

Last updated on August 15, 2024.

This article focuses on optimizing bitmaps for web properties and offers an overview of the steps involved in preparing images. Although it doesn't go into exhaustive details, it aims to share valuable experience and provide resource links to help you make the most of this knowledge.

Problem

One common issue in web development is dealing with heavy images that require significant downloading and rendering time. This results in increased data usage for mobile users and leads to longer waiting times, impeding users from quickly accessing the desired content on a webpage. On average, images account for around 60% of the total page weight, and as websites continue to expand, network speeds struggle to keep pace, particularly on mobile devices. Downloading and rendering images consume valuable time, while displaying large images on the screen further impacts memory usage.

Between 2011 and 2019, the median resource weight increased from ~100KB to ~400KB for desktop and ~50KB to ~350KB for mobile. While Image size has increased from ~250KB to ~900KB on desktop and ~100KB to ~850KB on mobile.

Source: MDN web docs - Lazy loading

Solutions

When optimising images, your goal is to strike a balance between minimising file size and meeting user expectations. However, determining what users will accept is subjective, requiring you to make decisions based on trade-offs. It would help if you weighed the advantages of faster load times and reduced bandwidth costs against the desire for visually appealing images. To make informed choices, consider why users visit your website and prioritise or deprioritise image quality accordingly.

Users tend to tolerate more quality degradation for purely decorative images such as backgrounds since they are not crucial content. While visually pleasing images are beneficial, ensuring they do not hinder webpage performance is equally important. Assessing the risk-to-reward ratio is crucial, and decisions regarding image quality should be made on a case-by-case basis.

On the other hand, when it comes to product photos, personal photographs (e.g., for photographers), or significant images that play a pivotal role on a page, it may be prudent to maintain image quality closer to the original, even when using lossy compression. These images represent crucial content that showcases products, tells a story, or aids in sales, making it essential to preserve their visual integrity.

Formats

This article focuses on raster images. However, it's important to note that if you have the vector source of an image, it is recommended to use SVG. SVG can be an excellent format for non-photographic images with fewer colours.

Now, let's explore the remaining bitmap formats:

  • (or ):
    This format is ideal for photographs. The more colours and gradients present, the better JPEG performs in terms of size/performance compared to PNG.
  • :
    Limited to 256 colors, GIF supports transparency.
  • :
    Use PNG for all other purposes, particularly when there aren't many colours involved (although JPEG may be more efficient in some cases). PNG is also suitable when an 8-bit alpha channel or lossless graphics are required.
  • :
    Despite being a promising and well-supported format, WebP is omitted due to the time and effort required to optimise for a few kilobytes in popular browsers. It is crucial to minimise risks and avoid potential bugs reported by users, as they are more likely to leave without reporting issues.

Please remember that user experience and compatibility should be key factors when selecting image formats for your web application.

Size

When dealing with images, avoiding wasting pixels and bandwidth is important. Consider the scenario where you have a 3000x4000px image but only display it as 300x400px. In this case, most of those pixels are unused, resulting in inefficient bandwidth usage.

Let's discuss an example: a product photo on a search list. On desktop, it is displayed as 400x200px, while on mobile, it occupies the screen's full width (say 600px) with the height adjusted proportionally. It's worth noting that pixel measurements have become subjective with the introduction of high DPI screens.

Here are a few approaches to consider:

  • Generate only the largest image you need:
    This is typically the preferred choice for most websites. If the difference between the smallest and largest image sizes is not substantial, generating only the largest image is recommended.
  • Generate one small, one medium, and one large image:
    This approach aims to target small, medium, and large screens. It is suitable when there is a significant difference in size between the images (at least 50%). For example, a small image could be 12 KB, a medium image 25 KB, and a large image 40 KB. If the difference is insignificant, omitting the medium image is advisable to maximise cache utilisation.
  • Generate all necessary variants, including high DPI:
    This approach is the most time-consuming and requires generating images for each desired variant, including high DPI versions. It also involves hardcoding image versions to breakpoints in the layout. This approach is recommended when there is a specific need, but it demands more computational resources and developer involvement.

It's important to note that multiple images require additional HTML and CSS code involvement. Learn how to implement multiple images based on screen size by referring to the resources provided for further reading at the end of this article.

Compression

In web development, many websites still rely on image formats invented over 20 years ago. However, this doesn't mean you can't make these images smaller. Algorithms such as and have demonstrated that there is still room for improvement in image compression.

You can employ three different methods for compressing images, depending on specific project requirements, the frequency of compression, and the level of image quality desired:

  1. ImageOptim:
    This method suits projects with ongoing developer supervision. It occasionally involves manual compression, particularly when images do not change frequently.
  2. sharp:
    As an extremely efficient compressor, sharp provides additional options, such as resizing. It can be used programmatically or as a command-line interface (CLI). You can rely on sharp when rapidly compressing a large volume of images. This approach is commonly used in high-performance applications where speed is critical, and operations on the image are necessary.
  3. imagemin:
    This method involves utilising the imagemin node package and its plugins, which wrap other image compressors, including pngquant, optipng, gifsicle, jpegtran, and more. Imagemin can be utilised as a webpack loader (imagemin-webpack), which is advantageous as the authors maintain all the necessary binaries for the most popular compressors. imagemin is employed in scenarios where projects lack constant developer supervision, allowing non-technical individuals to upload uncompressed images directly from their phones to the repository.

JPEG progressive

Setting the progressive attribute to is important when working with large JPEG images. Enabling progressive rendering improves the perceived speed of image loading, resulting in a better user experience.

For further information on progressive JPEGs, you can refer to the following resources:

Delivery

To optimise webpage loading times and improve user experience, it is advisable to implement lazy loading for images that appear below the fold. This technique ensures that images are only loaded when they are about to come into view, conserving valuable network resources.

If you're uncertain which images are suitable for lazy loading, a general guideline is to consider images below a specific threshold. For instance, measuring 1280px from the top of the page can be a reliable indicator for determining which images can be safely lazy-loaded.

To further enhance the loading experience, you can utilise image placeholders during the loading phase. You can create a smoother loading transition by displaying placeholders and updating the image source to the actual source. While this technique is not primarily intended for performance improvement, it can contribute to a better user experience, particularly for Single Page Applications. A prominent example of this approach is observed on platforms like YouTube.

For more information on implementing lazy loading and exploring additional strategies, please refer to resources that provide insights on built-in lazy loading techniques.

Example

As an example, download an example set of images (only JPEG) from a live webpage, save two copies, then run two tools on them - and .

The original set of images is exactly 7,514,494 bytes.

We then measure the time they took to compress the images and use relatively the same settings (quality 80).

Sharp result: (saved: bytes, or 27%) in seconds

imageoptim result: (saved: bytes, or 44%) in seconds

When utilising the library, note that you have the added benefit of resizing operations in a single step. This feature is a useful safeguard when dealing with image uploads from various sources, as it allows for efficient resizing based on the target dimensions required by your website.

While sharp demonstrates faster performance, it should be noted that the resulting output images may be larger in size. On the other hand, Imageoptim excels in compressing images, but the compression process is comparatively slower, almost ten times as long. Based on our experience, we recommend using Imageoptim for one-time optimisation tasks, such as optimising header images, logos, or team photos. We suggest using sharp for images that require synchronous uploading and demand a quick response time.

It is important to acknowledge that no automated image compression method is perfect. However, modern compressors employ advanced metrics like DSSIM (Structural Similarity Index) to ensure compression is as transparent and visually pleasing as possible to human viewers. Automated compression techniques are preferred for scenarios involving frequent image compression (more than one image per week) or projects lacking a dedicated developer for manual compression.

References

To assist you in optimising image files, please refer to the following resources:

Have a suggestion for this page?

Didn't quite find what you are looking for or have feedback on how we can make the content better then we would love to hear from you. Please provide us feedback and we will get back to you shortly.