Click here to see your recently viewed pages and most viewed pages.
Hide

Optimize Images

Configuration

The 'Optimize Images' filter stage comprises three filter passes. It is easiest to enable image rewriting by specifying:

Apache:
ModPagespeedEnableFilters rewrite_images
Nginx:
pagespeed EnableFilters rewrite_images;

in the configuration file. This is equivalent to enabling inline_images, recompress_images, convert_png_to_jpeg, and resize_images.

In every case, the image on the page is replaced by the optimized version only if the optimized version is actually smaller than the original.

The 'Optimize Images' filter won't optimize an image (though it might still cache extend it) if it has the pagespeed_no_transform attribute. Usage:

<img src="example.png" pagespeed_no_transform>

Enabling optimizations that are part of rewrite_images

You may enable image optimizations individually by specifying any number of the filters shown below.

Inline Images

Apache:
ModPagespeedEnableFilters inline_images
Nginx:
pagespeed EnableFilters inline_images;

This optimization replaces references to small images by an inline data: URL, eliminating the need to initiate another connection to fetch the image data.

As of 1.5.27.2, by default inline_images injects JavaScript that uses a beacon to report back to the server the images that are visible in the client's initial viewport (above the fold). It takes a few accesses of a page for the data to be reported back and processed but eventually the above-the-fold images will be known and will be inlined while all below-the-fold images will not be inlined; until then all small images will be inlined (and this is what the filter did prior to 1.5.27.2).

The use of beacons can be disabled using the ModPagespeedCriticalImagesBeaconEnabled directive. If they are disabled, inline_images will not inject the JavaScript and will revert to inlining all images (subject to its usual restrictions).

Recompress Images

Apache:
ModPagespeedEnableFilters recompress_images
Nginx:
pagespeed EnableFilters recompress_images;

This filter attempts to recompress image data and strip unnecessary metadata such as thumbnails. This is also a group filter, and is equivalent to enabling: convert_gif_to_png, convert_jpeg_to_progressive, convert_jpeg_to_webp, jpeg_subsampling, recompress_jpeg, recompress_png, recompress_webp, strip_image_color_profile, and strip_image_meta_data.

Again, these filters may be enabled or disabled individually:

Convert GIFs to PNG

Apache:
ModPagespeedEnableFilters convert_gif_to_png
Nginx:
pagespeed EnableFilters convert_gif_to_png;

This filter losslessly converts gifs to pngs. As a more modern image format, pngs can generally achieve higher compression than gifs. Animated gifs won't be converted because pngs can't animate.

Convert JPEG to Progressive

Note: before 1.2.24.1 this was not part of recompress_images and needed to be enabled separately.

Apache:
ModPagespeedEnableFilters convert_jpeg_to_progressive
Nginx:
pagespeed EnableFilters convert_jpeg_to_progressive;

When a jpeg is created by recompress_jpeg or resize_images, enabling convert_jpeg_to_progressive will transform larger non-progressive jpeg images (those more than 10KB in size) into progressive jpegs. Large progressive jpegs generally compress better and permit incremental display by the browser.

Recompress JPEGs

Apache:
ModPagespeedEnableFilters recompress_jpeg
Nginx:
pagespeed EnableFilters recompress_jpeg;

This filter recompresses jpegs in two different ways, depending on whether the input jpeg's quality higher or lower than PageSpeed's default output quality, which is ImageRecompressionQuality, or JpegRecompressionQuality if set. If the input image is higher quality than PageSpeed is set to produce then recompress_jpeg will recompress the image to the lower quality setting. Otherwise PageSpeed will attempt to improve the compression of the image but won't reduce its quality.

Recompress PNGs

Apache:
ModPagespeedEnableFilters recompress_png
Nginx:
pagespeed EnableFilters recompress_png;

This filter replaces pngs with ones encoded at a higher compression ratio. This is a lossless conversion.

Recompress WEBPs

Apache:
ModPagespeedEnableFilters recompress_webp
Nginx:
pagespeed EnableFilters recompress_webp;

This filter currently does not apply often because webp images are not yet widely adopted. But just like recompress_jpeg it replaces webp images with smaller webp images by re-encoding them at lower quality settings.

Strip Image Color Profile

Apache:
ModPagespeedEnableFilters strip_image_color_profile
Nginx:
pagespeed EnableFilters strip_image_color_profile;

This filter strips color profile information from images. Many browsers ignore color profiles, which means that sites already can't rely on them.

Strip Image Meta Data

Apache:
ModPagespeedEnableFilters strip_image_meta_data
Nginx:
pagespeed EnableFilters strip_image_meta_data;

This filter strips EXIF meta data from images.

Reduce JPEG Subsampling

Apache:
ModPagespeedEnableFilters jpeg_subsampling
Nginx:
pagespeed EnableFilters jpeg_subsampling;

This filter reduces the color sampling of jpeg images to 4:2:0. Human vision is much more sensitive to changes in brightness than changes in hue or saturation, and 4:2:0 color sampling allows us to keep brightness data while reducing the amount of hue and saturation data by 3/4. This can significantly reduce the image size while having only a small effect on perception.

Convert PNG to JPEG

Apache:
ModPagespeedEnableFilters convert_png_to_jpeg
Nginx:
pagespeed EnableFilters convert_png_to_jpeg;

Enabling convert_png_to_jpeg allows a gif or png image to be converted to jpeg if it does not have transparent pixels and if mod_pagespeed considers that it is not sensitive to jpeg compression noise. The conversion is lossy, but the resulting jpeg is generally substantially smaller than the corresponding gif or png.

Note: before 1.8.31.2 mod_pagespeed did not check whether the image was sensitive to compression noise and converted the image to jpeg as long as it did not have transparent pixels.

Resize Images

Apache:
ModPagespeedEnableFilters resize_images
Nginx:
pagespeed EnableFilters resize_images;

This attempts to resize any image that is larger than the size called for by the width= and height= attributes on the <img> tag or an inline style= attribute. The original image is replaced only if the image file is smaller after resizing. Image resizing is lossy by nature, regardless of image file format.

Note: It also strips color profiles and metadata even if strip_image_color_profile and strip_image_meta_data are disabled.

Note: If both resize_images and resize_rendered_image_dimensions are enabled then resize_rendered_image_dimensions takes precedence.

Other available image optimizations

Some image recompression options are not included in rewrite_images, the group filter, and so must be enabled specifically. They are:

Convert JPEG to WEBP

Apache:
ModPagespeedEnableFilters convert_jpeg_to_webp
Nginx:
pagespeed EnableFilters convert_jpeg_to_webp;

Enabling convert_jpeg_to_webp allows a jpeg image to be converted to a lossily-encoded webp if the brower supports this format ( list of browsers supporting webp). For browsers which do not support lossily-encoded webp, this option is ignored.

With this option enabled, a gif or png image can also be converted to a lossily-encoded webp if the configuration allows it to be converted to a jpeg (i.e., if convert_gif_to_png and convert_png_to_jpeg are also enabled), and if mod_pagespeed considers that the image is not sensitive to lossy compression noise. It does not matter whether the gif or png image has transparent pixels.

Note, before 1.8.31.2, if convert_to_webp_lossless was enabled, gif and png images were converted to losslessly-encoded webp even if they could be converted to jpeg.

Convert to WEBP lossless

Note: new feature as of 1.3.25.1

Apache:
ModPagespeedEnableFilters convert_to_webp_lossless
Nginx:
pagespeed EnableFilters convert_to_webp_lossless;

Enabling convert_to_webp_lossless allows a gif or png image to be converted to a losslessly-encoded webp if mod_pagespeed considers that the image is sensitive to lossily compression noise and if the brower supports losslessly-encoded webp ( list of browsers supporting webp). For browsers which do not support losslessly-encoded webp, this option is ignored. See Serving Webp URLs to any User Agent for more details on webp image serving policies.

Insert Image Dimensions

Apache:
ModPagespeedEnableFilters insert_image_dimensions
Nginx:
pagespeed EnableFilters insert_image_dimensions;

This flag inserts width= and height= attributes into <img> tags that lack them and sets them to the image's width and height. Note that this can cause image stretching or shrinking if CSS rules specify only one image dimension (see Risks below).

Resize images to rendered dimensions

Note: new feature as of 1.7.30.1

Apache:
ModPagespeedEnableFilters resize_rendered_image_dimensions
Nginx:
pagespeed EnableFilters resize_rendered_image_dimensions;

This attempts to resize any image to its rendered dimensions on the web page. Unlike resize_images it ignores any width and height attributes specified for the image. If the same image appears more than once on the page it is resized to the biggest rendered dimensions of the image. Similar to resize_images, the original image is replaced only if the image file is smaller after resizing. Image resizing is lossy by nature, regardless of image file format.

Note: It also strips color profiles and metadata even if strip_image_color_profile and strip_image_meta_data are disabled.

By default resize_rendered_image_dimensions injects JavaScript that uses a beacon to report back the rendered dimensions of all the images. It takes a few accesses of a page for the data to be reported back and processed but eventually the rendered dimensions for all the images will be known and will be used for resizing the images.

The use of beacons can be disabled using the ModPagespeedCriticalImagesBeaconEnabled directive. If they are disabled, resize_rendered_image_dimensions will not apply.

Note: If both resize_rendered_image_dimensions and resize_images are enabled then resize_rendered_image_dimensions takes precedence.

Inline Preview Images

The 'Inline Preview Images' filter generates low quality versions of the images that are inlined in the HTML page. Users experience faster rendering of the page and the low quality images are replaced by high quality versions after an onload event is triggered. More details.

Parameters that affect image optimization

ImageInlineMaxBytes

Apache:
ModPagespeedImageInlineMaxBytes MaxBytes
Nginx:
pagespeed ImageInlineMaxBytes MaxBytes;

MaxBytes, a positive integer, is the maximum size in bytes of any image that will be inlined into an HTML file. The current default value for MaxBytes is 2048.

CssImageInlineMaxBytes

Apache:
ModPagespeedCssImageInlineMaxBytes MaxBytes
Nginx:
pagespeed CssImageInlineMaxBytes MaxBytes;

Here MaxBytes, a positive integer, is the maximum size in bytes of any image that will be inlined into CSS. For inline CSS in HTML files, the value used is the smaller of MaxBytes or ImageInlineMaxBytes. The current default value for MaxBytes is 3072. It has been made separately settable because external CSS resources are often cacheable and can be shared between multiple pages, increasing the benefit of a high inlining threshold compared to non-cacheable, non-shareable html files.

ImageResolutionLimitBytes

Note: new feature as of 1.7.30.1

Apache:
ModPagespeedImageResolutionLimitBytes MaxBytes
Nginx:
pagespeed ImageResolutionLimitBytes MaxBytes;

Here MaxBytes, a positive integer, is the maximum size in bytes of an image that PageSpeed will try to optimize. By default the limit is 32 megabytes, at 4 bytes per pixel. The goal of this option is to control memory usage, which means it applies to uncompressed images. For example, consider a 2500x3500 image. It would have 8,750,000 pixels, each of which PageSpeed will use four bytes to represent, so at 35 megabytes it would be just above the limit. On disk, when saved in a compressed format, however, it would have a much smaller size, perhaps just 5MB. If PageSpeed is not optimizing your large images you may need to increase this limit, but be aware that this will use more memory and make sure you're staying within the capacity of your system.

RecompressionQuality

Note: new feature as of 1.1.23.1

Apache:
ModPagespeedImageRecompressionQuality Quality
Nginx:
pagespeed ImageRecompressionQuality Quality;

This option sets the compression quality used when creating or re-compressing jpeg and webp images. 0 indicates lowest quality, 100 highest. -1 indicates lossless recompression. Before 1.6.29.3 the default value was -1, now it defaults to 85. Note that jpeg and webp images compressed with the same quality settings will look different in general due to differences between the compression algorithms used.

JpegRecompressionQuality

Apache:
ModPagespeedJpegRecompressionQuality Quality
Nginx:
pagespeed JpegRecompressionQuality Quality;

This option sets the compression quality used when creating or re-compressing jpeg images, overriding any setting of ImageRecompressionQuality.

JpegRecompressionQualityForSmallScreens

Note: new feature as of 1.5.27.2

Apache:
ModPagespeedJpegRecompressionQualityForSmallScreens Quality
Nginx:
pagespeed JpegRecompressionQualityForSmallScreens Quality;

This option sets the compression quality used when creating or re-compressing jpeg images that will be viewed on devices with small screens (such as mobile phones). This option overrides JpegRecompressionQuality when PageSpeed determines that the client has a screen with an area no greater than 1280 x 800 pixels. Before 1.6.29.3 the default behavior was to use JpegRecompressionQuality for all screen sizes, but now a lower quality of 70 is used by default. Generally, a lower image quality can be used for small screens.

JpegNumProgressiveScans

Note: new feature as of 1.5.27.2

Apache:
ModPagespeedJpegNumProgressiveScans Scans
Nginx:
pagespeed JpegNumProgressiveScans Scans;

When convert_jpeg_to_progressive is enabled, images that are encoded as progressive JPEGs are first calculated to take ten scans to achieve the specified JPEG quality. This option, with values in the range [1,10], determines how many of those ten scans are included in the version of the image that is actually served to the client.

JpegNumProgressiveScansForSmallScreens

Note: new feature as of 1.5.27.2

Apache:
ModPagespeedJpegNumProgressiveScansForSmallScreens Scans
Nginx:
pagespeed JpegNumProgressiveScansForSmallScreens Scans;

When convert_jpeg_to_progressive is enabled, images that are encoded as progressive JPEGs are first calculated to take ten scans to achieve the specified JPEG quality. This option, with values in the range [1,10], determines how many of those ten scans are included in the version of the image that is actually served to the client. This option is specific to images that will be viewed on devices with small screens (such as mobile phones). This option overrides JpegNumProgressiveScans when PageSpeed determines that the client has a screen with an area no greater than 1280 x 800 pixels. The default behavior is to use JpegNumProgressiveScans for all screen sizes. Generally, a lower number of scans can be used for small screens.

ProgressiveJpegMinBytes

Note: new feature as of 1.7.30.1

When convert_jpeg_to_progressive is enabled, it is applied to images whose compressed size is estimated to be 10k bytes or larger. Converting images smaller than 10k to progressive often makes them larger. Note: the origin image might be somewhat larger than 10k, but compressed size is estimated based on the origin image and the desired compression settings. Use this setting to change the progressive jpeg threshold:

Apache:
ModPagespeedProgressiveJpegMinBytes min_bytes
Nginx:
pagespeed ProgressiveJpegMinBytes min_bytes;

WebpRecompressionQuality

Note: new feature as of 1.1.23.1

Apache:
ModPagespeedWebpRecompressionQuality Quality
Nginx:
pagespeed WebpRecompressionQuality Quality;

This option sets the compression quality used when creating or re-compressing webp images, overriding any setting of ImageRecompressionQuality.

WebpRecompressionQualityForSmallScreens

Note: new feature as of 1.5.27.2

Apache:
ModPagespeedWebpRecompressionQualityForSmallScreens Quality
Nginx:
pagespeed WebpRecompressionQualityForSmallScreens Quality;

This option sets the compression quality used when creating or re-compressing webp images that will be viewed on devices with small screens (such as mobile phones). This option overrides WebpRecompressionQuality when PageSpeed determines that the client has a screen with an area no greater than 1280 x 800 pixels. Before 1.6.29.3 the default behavior was to use WebpRecompressionQuality for all screen sizes, but now a lower quality of 70 is used by default. Generally, a lower image quality can be used for small screens.

Serving Webp URLs to any User Agent

Note: new feature as of 1.8.31.2

When PageSpeed rewrites an img tag in HTML or a background-url in CSS in response to a request from a webp-capable browser, it will often transcode the image to the webp format, and rewrite the URL using a .webp extension. If a site visitor then right-clicks on this image, copies the URL, and shares this URL with a friend, the URL might not work on older browsers. This is because, by default, PageSpeed will respond to that .webp URL with the webp image payload independent of the Accept or User-Agent header in the HTTP request headers.

Sites that place a high value on such URL sharing can make this work by disabling option ServeRewrittenWebpUrlsToAnyAgent:

Apache:
ModPagespeedServeRewrittenWebpUrlsToAnyAgent off
Nginx:
pagespeed ServeRewrittenWebpUrlsToAnyAgent off;

The limitation that prevents this switch from defaulting to off is that some proxy caches strip the User-Agent and Accept headers when transmitting requests for resources to origin. In that scenario, PageSpeed can't tell whether the browser requesting the image can display webp images. Thus it is not possible to have all three of these features at the same time:

  • Provide the best possible bandwidth and latency experience for visitors using modern browsers
  • Enable the sharing of URLs between visitors and their friends using older browsers
  • Use a proxy cache that strips User-Agent and Accept headers

If the first two features are important, the site needs to pick proxy cache technolgy or CDNs that don't strip User-Agent and Accept. Be sure to check with your proxy cache or CDN vendor to understand their policy on transmitting these headers.

ImageLimitOptimizedPercent

Apache:
ModPagespeedImageLimitOptimizedPercent Percent
Nginx:
pagespeed ImageLimitOptimizedPercent Percent;

The image optimizer keeps only optimized images whose size after recompression is less than the given percent of the original image size. For example, setting this to 95 will retain an optimized image only if it is at least 5% smaller than the original image it would replace. The default setting is 100, meaning any savings at all will cause the optimized image to be used. Do not set this to 0 to disable image optimization; disable recompress_images instead, or recompress_jpeg, recompress_png and recompress_webp for respective image formats.

ImageLimitResizeAreaPercent

Apache:
ModPagespeedImageLimitResizeAreaPercent Percent
Nginx:
pagespeed ImageLimitResizeAreaPercent Percent;

Only attempt to resize images whose area in pixels after optimization will be less than the given percent of the original image area. For example, setting this to 90 will only resize images if the image area shrinks by at least 10%. The default setting is 100, meaning any shrinkage at all will cause an image to be resized. Do not set this to 0 to disable image resizing; disable resize_images instead.

ImageMaxRewritesAtOnce

Apache:
ModPagespeedImageMaxRewritesAtOnce NumImages
Nginx:
pagespeed ImageMaxRewritesAtOnce NumImages;

This parameter limits the number of images being recompressed or resized at one time to NumImages. Because image optimization may be CPU-intensive it may be desirable to limit it to reduce the load on your server, especially at startup. Once optimized, images are cached until they expire. If an image cannot be optimized, this is remembered until expiration as well. When this parameter is not specified the current default value for NumImages is 8. Setting NumImages to 0 allows any number of images to be rewritten at once. If you wish to disable image optimization, you should instead disable resize_images and recompress_images, or its sub-parts recompress_jpeg, recompress_png and recompress_webp.

NoTransformOptimizedImages

Note: new feature as of 1.9.32.1

Apache:
ModPagespeedNoTransformOptimizedImages on
Nginx:
pagespeed NoTransformOptimizedImages on;

By default, PageSpeed-optimized resources will be served with response headers that allow proxies and browsers to cache them for a long time:

Cache-Control: max-age=31536000

Also by default, proxies are also free to recompress images further. This may be beneficial to the overall end-user experience because it can reduce bandwidth. However, if you are already using PageSpeed to compress images as much as possible, then you can prevent compliant proxies from further recompressing them by turning on this feature, resulting in responses with header:

Cache-Control: max-age=31536000,no-transform

Description

The 'Optimize Images' filter re-scales, re-compresses, and strips metadata from images referenced in <img> tags in a page. If rewrite_css is enabled, then images referenced from background-image, background, list-style-image and list-style CSS properties will also be optimized.

This reduces the number of bytes downloaded, often substantially; when no gain is realized, the filter leaves the original image unaltered. Image rewriting is particularly useful on image-heavy pages that have not been subjected to offline optimization, and on pages where images are shrunk implicitly by using width= and height= attributes or styles that are smaller than the image's actual dimensions.

The filter can also inline small image files by using the data: uri format. This does not happen on IE7 and earlier. Image inlining reduces the number of short-lived connections that are established during page download. When the containing html page is served with compression, image inlining also reduces the number of bytes downloaded by avoiding the need for additional headers. This practice reduces the payload size.

Operation

Image resizing (resize_images) shrinks images. Both resize_images and recompress_images use libjpeg_turbo and libpng to decode and re-encode images. recompress_jpeg uses libjpeg_turbo and recompress_png uses libpng. When convert_jpeg_to_webp is enabled, libwebp is used to create webp images. After any resizing and recompression are complete, inlining occurs if an image is smaller than ImageInlineMaxBytes (or CssImageInlineMaxBytes if the image is being referenced from CSS); inlining also strips out width and height attributes. If the image is not inlined, insert_image_dimensions inserts width and height if both are missing.

For example, if the HTML document looks like this:

<html>
  <head>
    <title>Image test example</title>
  </head>
  <body>
    <img src="images/Cuppa.png" width="65" height="70" alt="Inlinable Cuppa">
    <img src="images/BikeCrashIcn.png" alt="Bike Crash">
    <img src="images/Puzzle.jpg" width="256" height="192" alt="Scaled down puzzle">
  </body>
</html>

Then PageSpeed will rewrite it into:

<html>
  <head>
    <title>Image test example</title>
  </head>
  <body>
    <img src="data:image/png;base64,...Base64 data" alt="Inlinable Cuppa">
    <img src="images/BikeCrashIcn.png.pagespeed.ic.GSLMcHP-fl.png" alt="Bike Crash" width="100" height="100">
    <img src="images/256x192xPuzzle.jpg.pagespeed.ic.ryODdDEGKc.jpg" width="256" height="192" alt="Scaled down puzzle">
  </body>
</html>

You can see the filter in action at www.modpagespeed.com rewriting images in HTML and in CSS.

Requirements

Note that only jpeg, png, and non-animated gif images are re-compressed. Re-compressed gifs are translated into png files. There is no support planned for rewriting animated gifs.

Risks

Image rewriting is low to moderate risk. The most significant risk is that JPEG compression and image resizing are lossy; PageSpeed uses settings designed to preserve image quality, and this sometimes means eligible images are not re-compressed.

Image optimization (particularly resizing) may be CPU-intensive. You may find that your server load increases when images are being rewritten. This will be particularly noticeable immediately after server start. If load is unacceptably high, reduce ImageMaxRewritesAtOnce.

Image inlining is user-agent-sensitive; we do not inline images for older browsers that do not support the data: uri format.

The image rewriter strips out metadata from image files. Image metadata sometimes includes copyright information; this will be lost after re-compression. Note however that copyright information and watermarks on the image itself (in the image pixels) will not be materially affected.

Web designers use images as "beacons" to indicate certain kinds of page activity. These images must be uncacheable so that they are not rewritten.

Image recompression and resizing use deterministic algorithms based on popular open-source libraries. It is possible to craft an image that, after re-compression, looks like JavaScript or html to certain browsers. A cross-site scripting attack can then be launched using a <script> or <iframe> tag on another site, referring to the rewritten image URL. We recommend that user-submitted images be filtered before re-compression.

The insert_image_dimensions flag can cause an image to appear stretched if CSS rules specify exactly one dimension for that image. Normally for an <img> without width and height attributes such CSS rules will cause the image to be scaled in both dimensions, preserving the aspect ratio. When the filter inserts these attributes, the CSS rule will change only the dimension it specifies; the other dimension will retain its original size, causing the image to appear stretched. For example if the CSS rule specifies a smaller image height, the image would retain its original width and appear to be stretched horizontally.

To avoid this issue, specify both image dimensions in the CSS file, specify explicit width and height attributes that match those chosen by the CSS, use an overriding style attribute to specify image size, or disable insert_image_dimensions for affected pages.