Optimize Images

Introduction

The PageSpeed Modules optimize your images to minimize their size and thus reduce their load time. They remove non-visible image information and apply high-efficiency compression techniques. This can result in a data saving of 50% or more.

Using PageSpeed Modules, you can focus on the content of your site, knowing your visitors will receive images in the best format and dimensions for their device and browser while using minimum bandwidth.

Optimization methods

PageSpeed Modules can optimize most common image formats, including GIF, PNG, and JPEG, and convert them to PNG, JPEG, or WebP. GIF, PNG, and JPEG are supported by all browsers. WebP is a modern image format that can compress images over 25% more than older formats, and is currently supported by many browsers, including Google Chrome, Android 4.0+, and Opera. PageSpeed-optimized images are converted to the best format supported by the target browser, i.e., to WebP if it is supported, or PNG or JPEG if not.

PageSpeed can also maximize compression based on image content. Lossy formats compress images far better than lossless formats, but sometimes introduce visible and undesirable "compression noise". PageSpeed examines the content of images to see whether they are sensitive to compression noise and, if so, converts to PNG or the lossless mode of WebP; if not, it converts to JPEG or the lossy mode of WebP.

In-place optimization vs. tag rewriting

PageSpeed is capable of doing all this without changing your HTML or CSS, known as In-Place Resource Optimization (IPRO). However, if you allow PageSpeed to modify your HTML and CSS, it can do even more. For example, PageSpeed can shrink images to their actual rendered dimensions, thereby using fewer pixels and offering additional byte savings. It can also inline small images into HTML or CSS to avoid additional round trips to your server for fetching the images.

This table shows some examples of how PageSpeed can modify your HTML.

Example 1
Before optimization <img src="images/Image1.gif"/>
After optimization <img src="images/xImage1.gif.pagespeed.ic.GSLMcHP-fl.png"/>
Explanation Image converted from GIF to PNG format and cache-extended.
Example 2
Before optimization <img src="images/Image2.png" width="256" height="192"/>
After optimization <img src= "images/256x192xImage2.png.pagespeed.ic.ryODdDEGKc.png" width="256" height="192"/>
Explanation Image resized to 256 x 192 pixels, recompressed to PNG, and cache-extended.
Example 3
Before optimization <img src="images/Image3.jpg" width="65" height="70"/>
After optimization <img src="data:image/jpeg;base64,...Base64 data"/>
Explanation Image resized and then inlined into HTML as Base64 data. Because the inlined data has the desired dimensions, width and height are no longer needed.

Tip: There are multiple ways to tell PageSpeed Modules not to modify certain images.

Image formats

PageSpeed Modules support the most common image formats used on the web.

GIF A legacy but still popular image format. GIF is a lossless format, so the compressed image is visually identical to the original. It supports both single frame (still image) and multiple frames (animation). Despite its popularity, GIF often has poor compression performance, so PageSpeed converts GIF images to other (better) formats, unless the images are tiny.
PNG A more recent lossless format designed as a successor to GIF for single-frame images.
JPEG A lossy format where the compression process removes image detail that is difficult for the human eye to see. How much data to remove depends on the quality level. JPEG has two modes, baseline and progressive. Progressive mode can be used to render the image incrementally and has a higher compression ratio for large images.
WebP A cutting-edge image format. While it is not yet supported in all browsers, it is becoming increasingly available. In addition to superior compression performance, it includes features of all other formats: lossy mode, lossless mode, transparency, and animation. WebP has added support for these features over time, so your visitor's browser may support all, a subset, or none of these features. PageSpeed automatically detects the features which your visitor's browser supports and only uses the supported features in optimization.

Filters

PageSpeed Modules provide specific filters so you can control exactly how your images are optimized. For each visitor, PageSpeed Modules choose the best format and mode from the ones you allowed and the ones supported by the visitor's browser.

To simplify configuration, PageSpeed Modules provide rewrite_images, a filter group that consists of the most common image optimizations. It allows recompression, transcoding to optimal formats, reduction of image dimensions, and inlining of small images into HTML or CSS. If you want to make more detailed adjustments, you can also enable or disable the individual filters:

You can use any combination of the filter group and individual filters for your site. In each case, images are optimized only to the formats that are supported by your visitor's browser, and images are replaced only when the optimized one is smaller than the original.

Image quality

For images that are sensitive to compression noise, PageSpeed Modules always use lossless compression; for other images, PageSpeed Modules use the more aggressive lossy methods. For the lossy formats you can specify up to three quality levels, indicated by specific situations:

If your visitors have high transfer costs, slow connection speeds, or for other reasons, they may prefer reduced data usage. Some browsers, including Chrome, Opera, and Yandex, let visitors choose to send a Save-Data header when they request pages. You can honor their preference by allowing lower image quality for such requests.

The image quality levels can be specified using various parameters, listed here in order of precedence.

  1. Format-specific qualities for save-data: JpegQualityForSaveData and WebpQualityForSaveData.
  2. Format-specific qualities for mobile: JpegRecompressionQualityForSmallScreens, WebpRecompressionQualityForSmallScreens, and WebpAnimatedRecompressionQuality.
  3. Format-specific qualities for all other cases: JpegRecompressionQuality, WebpRecompressionQuality, and WebpAnimatedRecompressionQuality.
  4. Format-generic quality for all other cases: ImageRecompressionQuality.

Each parameter has a range of 0 - 100, representing lowest to highest quality. They can also be set to -1, indicating that the parameter should be ignored and the parameters of the lower precedences should be used. If all of the quality parameters are set to -1, images will not be optimized to any lossy format.

Tip: If you do not want to recompress lossy-format images or convert images to lossy formats, it is best to disable any filter that would optimize to JPEG or WebP. Setting all of the qualities to -1 wastes CPU to achieve the same result.

Image dimensions

PageSpeed Modules can shrink an image to its actual display dimensions based on the design of the page, the visitor's device, and the visitor's actions, to ensure the best user experience without wasting pixels.

You can use the resize_images filter to shrink the image to the dimensions specified by the width= and height= attributes in the <img> tag or by the inline style= attribute.

If you cannot use the resize_images filter, you can use the resize_rendered_image_dimensions filter to shrink the images to their rendered dimensions. In this case, PageSpeed injects JavaScript into your HTML that will report the rendered dimensions to the server, known as "beaconing". After receiving a few beacons, PageSpeed identifies the dimensions, and shrinks the images.

You can use the responsive_images filter to ensure your visitor sees full-resolution images, whether they are using a retina-based or regular device. Sending full resolution images to all devices is challenging because different devices may use a different number of pixels (known as device pixels) for displaying a region of the page (measured by CSS pixels). For example, a region of 100x100 CSS pixels in a page is displayed using 100x100 device pixels on an iPhone 3, 200x200 device pixels on an iPhone 6, and 300x300 device pixels on an iPhone 6+. For the best visual effect using the least bandwidth, you can resize your image to 100x100 for iPhone 3, to 200x200 for iPhone 6, and to 300x300 for iPhone 6+. Using this filter, PageSpeed generates images at all of these dimensions, and then modifies the <img> tags so your visitor's browser uses the best size.

Taking the responsive_images filter one step further, you can use the responsive_images_zoom filter to send images of higher resolutions when your visitor zooms in. Using this filter, PageSpeed injects JavaScript into your HTML that checks the zoom level of the page and fetches a higher-resolution image if necessary. On the back end, PageSpeed resizes the image to the proper resolutions.

Inline images

In addition to making the images smaller, PageSpeed Modules can help your page load faster by inlining images or previews into your HTML or CSS.

PageSpeed can inline small images directly into the HTML or CSS, reducing server requests. This is enabled by the inline_images filter, and is controlled by the ImageInlineMaxBytes and CssImageInlineMaxBytes options.

As well as inlining small images, PageSpeed can inline a reduced-quality version of large images into the HTML or CSS and, after the page is loaded, replace the low-quality image with the original. See Inline Preview Images for details.

Srcsets

Note: New feature as of 1.12.34.1.

In addition to optimizing image src attributes, as of 1.12.34.1 PageSpeed will now also optimize images referenced in srcsets. This includes all PageSpeed image optimizations except resizing.

PageSpeed can also automatically insert srcset attributes. See the the responsive_images filter for configuration instructions.

Other controls

PageSpeed Modules provide controls to make sure that your server is stable, your proxy/CDN (if any) is fully utilized, and your images are delivered to the user in the format you want.

Image optimization is an expensive process. To ensure the stability of your server, you can use ImageResolutionLimitBytes to limit the maximum dimensions of images to optimize, and ImageMaxRewritesAtOnce to limit the maximum number of images that are concurrently optimized.

To ensure that your proxy/CDN can handle the optimized images correctly, you can use AllowVaryOn to tell PageSpeed which request headers can be used to control image optimization. You can also use NoTransformOptimizedImages to instruct proxies not to further compress the images.

The ServeRewrittenWebpUrlsToAnyAgent option can be used to tell PageSpeed how to respond to a request asking for a WebP image when the browser does not appear to support WebP. In this case, PageSpeed will normally return the image as a PNG or JPEG (whichever is most appropriate). If ServeRewrittenWebpUrlsToAnyAgent is enabled, PageSpeed will instead return the WebP unconditionally. Returning the image depending on the headers ensures that your visitor sees the image correctly. Returning the image unconditionally in WebP format is useful if you want to serve WebP but your CDN or proxy removes headers from the request.

You can also ask PageSpeed to insert the image dimensions into <img> tags so the browser can compute the layout of the page before downloading the images. See insert_image_dimensions filter for more information.

Risks

Image optimization is not perfect, and its use can have some downsides. Here are some potential issues and suggested solutions.

Image optimization is both CPU- and memory-intensive.

You will probably see your server load increase while images are being rewritten, particularly immediately after server start. If the load increases too much, you can alleviate it by setting ImageMaxRewritesAtOnce and ImageResolutionLimitBytes. After the images have been optimized once, they will be cached for future use.

Reducing the dimension of an image or compressing it to a lossy format causes some image details to be lost.

This is sometimes noticeable, though usually not; you should inspect the optimized images to ensure their quality is acceptable.

PageSpeed removes metadata, such as copyright information.

If you want keep a specific image's metadata, add data-pagespeed-no-transform attribute. PageSpeed does not remove watermarks.

It is possible to craft an image that, after re-compression, looks like HTML to certain browsers.

While PageSpeed adds proper content-type headers and headers that forbid content-type sniffing, some ancient browsers can still be tricked into rendering them as HTML. If you have user-submitted images, you should filter them before using them in your site.

Your beacons may need a new attribute.

If you use images as beacons to monitor page activity, you should add data-pagespeed-no-transform attribute to them. Otherwise, PageSpeed may optimize the images and the activity will not be reported to you.

Images may incur stretching distortion if you ask PageSpeed Modules to insert image dimensions.

If you use insert_image_dimensions on pages where your CSS modifies image sizes, the images may appear distorted. Again, inspect compressed images for render dimensions.

Color profiles are removed by PageSpeed.

If your images contain color profiles, they are removed to save data. This is usually not a problem since most images with a color profile render indistinguishably when the color profile is removed.