Optimize Images

Introduction

PageSpeed optimizes your images to minimize their size based on the visitor's browser and preferences, and based on the content of the images. It removes non-visible image information before applying high-efficiency compression techniques. In our experiments, we have seen these techniques together save over 56% of data transfer for typical websites.

PageSpeed can optimize the most common image formats (GIF, PNG, JPEG, and WebP), including transparent and animated versions. The images are optimized to the best format which is supported by the browser. In most cases that's WebP, a modern image format that can typically compress images 25+% better than older formats. However, WebP is only supported by modern browsers including Google Chrome, Android 4.0+, and Opera. PageSpeed can automatically detect whether your visitor’s browser supports WebP. If it does, PageSpeed optimizes your images to WebP format; if not, PageSpeed will use PNG or JPEG which are universally supported.

In addition to maximizing the capability of the browser, PageSpeed also maximizes compression based on image content. Lossy formats can compress images more than 10 times better than lossless formats, but sometimes introduce ugly “compression noise”. PageSpeed examines the content of images to see whether they are sensitive to compression noise. If not, it optimizes your images to lossy formats including JPEG or the lossy mode of WebP. For sensitive images, PageSpeed will use PNG or the lossless mode of WebP.

PageSpeed can do all the above-mentioned optimizations to your images without changing your HTML, CSS, or JavaScript files. This mode is known as In-Place Resource Optimization for images. If you allow PageSpeed to modify your HTML and CSS files, however, PageSpeed can do more optimizations. For example, PageSpeed can shrink your images to their actual rendered dimensions, using fewer pixels. PageSpeed can also inline small images into HTML or CSS, to avoid initiating new connections for fetching the images. Here is an example of how PageSpeed can modify your HTML.

Before optimization:

<img src="images/Image1.gif"/>
<img src="images/Image2.png" width="256" height="192"/>
<img src="images/Image3.jpg" width="65" height="70"/>

After optimization:

<img src="images/xImage1.gif.pagespeed.ic.GSLMcHP-fl.png"/>
<img src="images/256x192xImage2.png.pagespeed.ic.ryODdDEGKc.png"
     width="256" height="192"/>
<img src="data:image/jpeg;base64,...Base64 data">

Transformations:

  • Image1.gif was converted from GIF format to PNG for better compression.
  • Image2.png was resized to 256-by-192 pixels and recompressed.
  • Image3.jpg was resized and then inlined into HTML as Base64 data. Because the inlined data has the desired dimension, width= and height= attributes are not needed anymore.

If you have particular images that you don't want PageSpeed to modify, you can add the data-pagespeed-no-transform attribute. For example:

<img src="do-not-modify.png" data-pagespeed-no-transform/>

With PageSpeed you can focus on the contents of your site, knowing your visitors will receive your images in the best format and right dimensions, with the minimum use of bandwidth.

Image formats

PageSpeed supports the image formats most common on the internet: :

  • GIF: An ancient but still popular image format. It is a lossless format, so the compressed image is 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 it removes depends on the quality level. JPEG has two modes: baseline and progressive. Compared to baseline, progressive mode can be used to render the image incrementally and has a higher compression ratio for large images.
  • WebP: WebP is a cutting-edge image format. While it's not currently supported in all browsers, it's becoming increasingly available. In addition to superior compression performance, it has all features of other formats: lossy mode, lossless mode, and transparency and animation support. WebP added support for these features over time, so PageSpeed automatically detects whether the browser supports WebP, and if it does, which features it supports.

PageSpeed provides fine-grained filters so you can control exactly how your images will be optimized. For each visitor, PageSpeed chooses the image format and mode that will get the best compression out of the ones their browser supports and you've allowed.

PageSpeed provides two filter groups.

  • recompress_images: Filters which are recommended for the In-Place Resource Optimization mode. These filters do not have to modify your HTML or CSS, and the result can be handled by CDN.
  • rewrite_images: Filters that go a step farther, making additional optimizations that require modifications to your HTML or CSS. In addition to all of the filters in recompress_images, this group also resizes images, inlines small images into HTML or CSS, and losslessly converts image to WebP.

If you want to make more detailed adjustments, you can also enable or disable individual optimization filters:

You can use any combination of the filter groups and individual filters for your site. In every case, your image will only be optimized to the formats which are supported by your visitor’s browser, and your image will be replaced only when the optimized one is smaller than the original.

Image quality

For images which are sensitive to compression noise, PageSpeed will only use lossless compression. With images that are not so sensitive, PageSpeed will use the more aggressive, lossy methods. For the lossy formats you can specify up to 3 quality levels, for the following situations:

  • When the user indicates a preference for reduced data usage.
  • When the user visits your site from a mobile device. Mobile devices usually have a high device pixel ratio so compression noise is less visible. In addition, mobile devices are more likely to be using an expensive data channel.
  • For all other cases, e.g., when the user visits your site from the desktop or tablet.

When your visitor has high transfer costs, slow connection speeds, or for other reasons, they may prefer reduced data usage. Some browsers, including Chrome and Opera, let users choose to send a Save-Data header when they request pages. You can honor your visitor’s preference by setting low image qualities for such requests.

The qualities can be specified using the following parameters:

  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.

Parameters listed earlier have higher precedence. Each of these parameters can be in the range of [0, 100] or -1. Values of 0 and 100 correspond to the lowest and highest qualities, respectively. Value of -1 means that this specific parameter should be ignored and the more general one should be used.

If you do not want to recompress your lossy-format image, or convert image to lossy format, do not enable any filter for optimizing images to JPEG or WebP.

Resize image dimensions

PageSpeed can shrink your image to its actual display dimensions, based on the design of your page, your visitor’s device, and your visitor’s action, to ensure the best user experience without wasting any pixels.

  • You can use the resize_images filter to srhink the image to the dimensions specified by the width= or height= attribute in the <img> tag or the inline style= attribute,
  • 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, for beaconing back the rendered dimensions. After receiving a few beacons, PageSpeed identifies the dimensions, and shrinks the images.
  • You can use the responsive_images filter to ensure your visitor see full resolution images, no matter whether he/she uses a retina or regular device. Sending full resolution images to all devices is challenging because devices may use a different number of pixels (known as device pixel) for displaying a region in your page (measured by CSS pixels). For example, a region of 1x1 CSS pixels in your page is displayed by 100x100 device pixels in iPhone 3, by 200x200 device pixels in iPhone 6, and by 300x300 device pixels in iPhone 6+. For the best visual effect and the least use of bandwidth, you can resize your image to 100x100 for iPhone 3, to 200x200 for iPhone 6, and to 300x300 for iPhone 6+. With the responsive_images filter PageSpeed generates images of all these dimensions, and modifies the <img> tags so your visitor’s browser will use the best size.
  • You can use the responsive_images_zoom filter to send images of higher resolutions when your visitor zooms in. With this, PageSpeed injects JavaScript to your HTML. The JavaScript checks the zoom level of your page, and fetches image of higher resolution if necessary. On the backend, PageSpeed resizes the image to the proper resolutions.

Inline images into HTML or CSS

Besides making the images smaller, PageSpeed can make your page faster to load by inlining the images or preview of the images, into your HTML or CSS.

  • PageSpeed can inline small images directly into the HTML or CSS, eliminating several round trips. This method can be enabled by the inline_images filter, and is controlled by the ImageInlineMaxBytes and CssImageInlineMaxBytes options.
  • PageSpeed can inline a reduced quality copy of large images into the HTML or CSS, and once the page has been loaded (i.e., after the onload event) PageSpeed replaces the low quality image with the original one. See Inline Preview Images for details.

Other controls

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

  • Image optimization is a computationally expensive process. To ensure the stability of your server, you can use ImageResolutionLimitBytes to limit the maximum dimensions of image to optimize, and ImageMaxRewritesAtOnce to limit the maximum number of images which 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 when optimizing an image. PageSpeed then chooses the minimum set of headers needed for a given image. You can also use NoTransformOptimizedImages to instruct proxies not to further compress the images.
  • You can use the ServeRewrittenWebpUrlsToAnyAgent option to tell PageSpeed how to respond to a request asking for a WebP image: returning the image in PNG/JPEG format if the request did not include the supporting user-agent and accept headers, or returning the image in WebP format unconditionally. Returning the image depending on the headers ensures that your visitor sees the image correctly. Returning the image unconditionally in WebP format minimizes your bandwidth, if your CDN or proxy may remove the 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 your page before downloading the images. See insert_image_dimensions filter.

Risks

  • Image optimization is both CPU and memory intensive. You will probably see your server load increase while images are being rewritten. This will be particularly noticeable immediately after server start. If load increases excessively, you can alleviate this problem by setting ImageMaxRewritesAtOnce and ImageResolutionLimitBytes. Once the images have been optimized, they will be cached for future use.
  • Changing the size of an image or compressing it to a lossy format causes some details of the image to be lost. You can inspect the optimized images to ensure their quality is acceptable.
  • In general, PageSpeed removes metadata, such as copyright and color profile, from the image. If you want keep the metadata for a particular image, add the data-pagespeed-no-transform attribute to it. PageSpeed doesn't 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 older browsers can still be tricked into rendering them as HTML. If you have user-submitted images, we recommend you filter them before using them in your site.
  • If you use images as "beacons" to indicate certain kinds of page activity, add data-pagespeed-no-transform attributes to them, so the activity will be reported back directly to you instead of to PageSpeed.
  • If you use insert_image_dimensions on pages where your CSS modifies image sizes, your images may have stretching distortion.
  • Color profile, if included in your image, will be removed. However, most browsers ignore color profile anyway.