Movatterモバイル変換


[0]ホーム

URL:


  1. Home
  2. Reference documentation

Image Optimizer reference

The FastlyImage Optimizer (IO) manipulates and transforms images as they pass through the Fastly network, and caches optimized versions of them.

IO shielding illustration

IO interacts with thefetch node in theshield POP (seeclustering andshielding). IO-enabled requests that ultimately load an image from origin will transit the shield fetch node twice. This results in both the original and the transformed image being cached at the shield, while just the transformed image will be cached at the edge.

IMPORTANT: If using custom VCL, be aware that at the shield POP, VCL subroutines that normally run on a fetch node (vcl_miss,vcl_pass, andvcl_fetch) will runupstream (i.e., on the origin side) of the image optimizer. As a result, these subroutines handle the request for the original image, while all other VCL subroutines on the shield POP (and all subroutines on the edge POP) are part of the request for the transformed image.

Enabling image optimization

Image optimization is an optional upgrade to Fastly service plans. If you have not yet purchased IO,contact sales.

If your Fastly account is entitled to use image optimization, it can be enabled on an individual servicein the web interface or by enabling theimage_optimizer product using theproduct enablement API.

  1. CDN services
  2. Compute services

Once enabled, you can trigger Fastly to pass a request through the image optimizer by adding theX-Fastly-Imageopto-Api header invcl_recv. This is usually done conditionally, so that it applies only to image requests:

sub vcl_recv { ... }
Fastly VCL
if (req.url.ext~"(?i)^(?:gif|png|jpe?g|webp|avif|jxl|heic)\z"||req.url.path~"^/images/") {
setreq.http.X-Fastly-Imageopto-Api="fastly";
}

HINT: Typically requests are flagged for IO processing using a path match as above, but if you prefer you can alsouse the content-type of the response.

Services that use image optimization are required to enableshielding.

These steps can also be performedvia the web interface.

Other options may also be specified in theX-Fastly-Imageopto-Api header value. Seecaching below.

WARNING: IO will only process requests that are eligible for caching. Seelimitations.

Default behavior

Enabling IO will activate a set of standard transformations and filters intended to provide 'good defaults' that will not change the image's dimensions or visual fidelity. You canmodify these in the web interface. Many of these can be further overridden or customized by providing explicitconfiguration directives as query parameters or headers:

  • jpg,pjpg, andwebp images will optimized automatically with default quality of 85.
  • All metadata (for example, EXIF, XMP, C2PA manifests, or ICC) will be removed.
  • If the image contains an ICC profile, the data will be applied directly to the image to ensure color output is correct. If the image doesn't contain an ICC profile, a default profile is added. These behaviors do not apply topng orwebp images.
  • If the source image contains orientation metadata, this orientation will be applied directly to the image data and metadata will be removed.
  • The originalVary response header from origins will be removed by IO. Seelimitations.

Configuration

Often the default transformations will save a significant amount of data without any further effort, but you can customize the behavior with query parameters and headers. For example, the following query string will direct the IO processor to resize the image to 300 pixels wide and crop it to a 16:9 ratio, centered on the most important visual content, including the detection of faces:

/image.png?width=300&crop=16:9,smart

Query parameters

We recognize the following parameters in the query string of the image request:

ParameterDescription
autoEnable optimization features automatically.
bg-colorSet the background color of an image.
blurSet the blurriness of the output image.
brightnessSet the brightness of the output image.
bwConvert an image to black and white.
canvasIncrease the size of the canvas around an image.
contrastSet the contrast of the output image.
cropRemove pixels from an image.
disableDisable functionality that is enabled by default.
dprServe correctly sized images for devices that expose a device pixel ratio.
enableEnable functionality that is disabled by default.
fitSet how the image will fit within the size bounds provided.
formatSpecify the output format to convert the image to.
frameExtract the first frame from an animated image sequence.
heightResize the height of the image.
levelSpecify the level constraints when converting to video.
metadataControl which metadata fields are preserved during transformation.
optimizeAutomatically apply optimal quality compression.
orientChange the cardinal orientation of the image.
padAdd pixels to the edge of an image.
precropRemove pixels from an image before any other transformations occur.
profileSpecify the profile class of application when converting to video.
qualityOptimize the image to the given compression level for lossy file formatted images.
resize-filterSpecify the resize filter used when resizing images.
saturationSet the saturation of the output image.
sharpenSet the sharpness of the output image.
trimRemove pixels from the edge of an image.
viewboxRemove explicitwidth andheight properties in SVG output.
widthResize the width of the image.

Header parameters

HeaderDescription
X-Fastly-Imageopto-MontageCombine up to four images into a single displayed image.
X-Fastly-Imageopto-OverlayOverlay one image on top of another image.

Processing order

Although the parameters can be specified in any order, we normalize the transformation sequence within our system to the following order:

  1. precrop
  2. trim
  3. crop
  4. orient
  5. widthheightdprfitresize-filterdisableenable
  6. padcanvasbg-color
  7. brightnesscontrastsaturationbw
  8. sharpen
  9. blur
  10. X-Fastly-Imageopto-Overlay
  11. formatautooptimizequalityprofilelevelmetadata

If anX-Fastly-Imageopto-Montage header is specified, all other IO parameters and headers are ignored.

Caching

The original image is only requested and cached once, even if distinct requests might demand versions of the image that are transformed differently.

For example, a user on a desktop device triggers a request forimage.png?width=1600, while a different user on a mobile device requestsimage.png?width=400. These requests are considered to be different for the purposes of caching transformed images and will result in different cache objects, but the request to origin isimage.png (with no query parameters). Each transformation is cached as a variant of the original image, and thus the total number of unique transformations is subject to the Vary objectscount limit.

IMPORTANT: Image optimization will only be applied to cacheable responses, and for services created on or after May 2, 2023, a minimum cache TTL of 60 seconds is enforced on transformed images (the original image is also cached and has no minimum TTL).

A request with image optimization enabled cannot make use of cached content created by a request that did not have image optimization enabled. Activating a configuration that enables IO on a large number of images may therefore result in a temporary, sharp decrease in cache hit ratio and corresponding increase in traffic to origin. Seeenabling features gradually if you need to avoid this.

Query string removal

By default,all query parameters are stripped, even those that are not recognized by the image optimizer. You can, however, allow passthrough of unknown query parameters.

  1. CDN services
  2. Compute services

Opt in to query parameters by changing the value of theX-Fastly-Imageopto-Api header:

setreq.http.X-Fastly-Imageopto-Api="fastly; qp=*";

With this opt-in enabled, a request forimage.png?width=300&something=foo would trigger the original image to be loaded from your origin server with a request URI ofimage.png?something=foo. The known parameter has been removed, but the unknown parameter was passed through.

WARNING: Enabling theqp=* override may reduce the image cache hit ratio and increase traffic to your origin servers.

Purging images from the Fastly cache

  1. CDN services
  2. Compute services
The query string normalization described above happens prior to the `vcl_hash` subroutine and the IO query parameters are saved in a secondary hash to allow separation of the variants. This allows all variants of the same image to be purged in a single request.

To purgethe original image and all variants, make a purge request without IO parameters:

$ curl -X PURGE https://example.com/image.jpg

It is not possible (and likely never desirable) to purge a single, transformed variant (because a subsequent request for that variant would produce the same result). It is also not possible to purge an original image without purging the transformed images, because subsequent requests would potentially result in caching an inconsistent set of images.

Testing and debugging

When images pass through the IO processor, it will add a header calledfastly-io-info with the following form:

fastly-io-info:ifsz=108501 idim=827x788 ifmt=jpeg ofsz=13066 odim=300x286 ofmt=jpeg

This header provides detail on the input format (ifmt), dimensions (idim), and size in bytes (ifsz), and also the output format (ofmt), dimensions (odim), and size in bytes (ofsz).

Click 'RUN' on the interactive demo below to create an ephemeral Fastly service and make a request through it for an image of former US president Barack Obama.

In this demo, we also show how to calculate the size ratio between the original image and the transformed image by post processing thefastly-io-info header, dividingofsz byifsz, and multiplying by 100 to yield a percentage.

Errors and warnings

If an error occurs during image processing, afastly-io-warning orfastly-io-error header is added to the response. The following error scenarios will prevent the image from being processed:

  • Image exceeds maximum dimensions
  • Image could not be parsed
  • Not a supported image format
  • Not specifying an output format for anHEIC source image
  • Unsupported Content-Encoding
  • Gzipped body exceeds maximum length
  • Gzipped body could not be decoded
  • Invalid status
  • Response is pass
  • Response is not cacheable
  • SVG output exceeds 50MB

Authenticating IO requests

You may prefer not to expose image optimization parameters publicly. For example, allowing raw image transform parameters to be accepted on inbound client requests may allow an end users to gain access to a higher resolution of your source images than you had intended. One solution is to implement transformation classes. In this example, we map some precomposed IO queries to general labels like "large", "medium", and "small", so that the image request from the client is?class=large rather than?crop=16:9,smart&width=640.

  1. CDN services
  2. Compute services

While not essential, the demo above also includes logic to remove any query parameters that are not the customclass param, preventing end-user customization of the IO behavior.

Lossy vs. lossless output

IO supports both lossy and lossless images for input and output. Lossless output is available forJPEGXL andWebP as well asPNG andGIF, which are lossless formats to begin with. If your source image is a lossless format, the output automatically defaults to lossless if the specified output format allows it. This means when using aPNG source withformat=webp,format=jxl, orformat=auto, the output image is lossless by default.

IO does not support lossless output forAVIF.

Forcing lossy output

Lossless output preserves all image data which also means it produces larger file sizes. This may be undesirable when delivering images over the web. To ensure lossy output in cases when your source format is lossless:

  • Useformat=auto with aquality value less than100 which also intelligently chooses the output format.
  • Useformat=webply for lossyWebP.
  • Useformat=jxl with aquality value less than100 for lossyJPEGXL.

Forcing lossless output

To force lossless output even in cases where your source image is lossy:

  • Useformat=auto withquality=100.
  • Useformat=webpll for losslessWebP.
  • Useformat=jxl withquality=100 for losslessJPEGXL.

Using optimized images and videos in HTML

The Fastly Image Optimizer allows you to generate images to suit the way you want to lay them out on the client device, but it's up to you to prompt the client device to request the most appropriate image variant. If your client device is a web browser and you are serving HTML, then you can make use ofresponsive images web technologies.

Pixel density

Using thesrcset attribute, it's possible to define images to be used at differentdisplay pixel densities, which works well with thewidth anddpr parameters.

<imgsrcset="/io-demo/image.jpg?width=320&dpr=1.5 1.5x,
/io-demo/image.jpg?width=320&dpr=2 2x"
src="/io-demo/image.jpg?width=320"/>

Art direction

Use the HTML5<picture> element to deliver different image crops at different browser viewport sizes, a technique calledart direction:

<picture>
<sourcesrcset="/io-demo/image.jpg?width=600&crop=16:9"media="(min-width: 600px)"/>
<imgsrc="/io-demo/image.jpg?width=320&crop=1:1"/>
</picture>

Image type

The<picture> element can also be used to provide different formats, allowing the browser to choose a format that best suits its needs and is compatible with the formats that it supports:

<picture>
<sourcetype="image/webp"srcset="/io-demo/image.webp"/>
<sourcetype="image/png"srcset="/io-demo/image.png"/>
<imgsrc="/io-demo/image.jpg"/>
</picture>

Learn more aboutwhich image formats are supported in which browsers.

Replacing GIFs with inline video

The animated GIF format benefits from being universally compatible and plays inline on all major web browsers. However, with the introduction of theplaysinline attribute, the<video> element is now usable in most of the same use cases as GIF. Video formats typically offer far better compression than GIF, and the Image Optimizer can be used to convert existing GIFs into MPEG 4 video:

<videowidth="300"height="224"playsinlineautoplaymutedloop>
<sourcesrc="/io-demo/image.gif?format=mp4"type="video/mp4"/>
</video>

Origin failover

Sometimes you may want to have more than one origin, often for redundancy purposes (e.g., primary: Amazon S3, secondary: Google Cloud Storage). If a resource does not exist in the primary origin, or the primary is unavailable, then we can perform arestart and try the secondary origin. We have acode example showing how to do this for normal resources, but there are some caveats to implementing this solution with IO:

  • With IO enabled, query parameters will be stripped from the request URL aftervcl_hash, so won't be present on the restarted request. This can be solved by storing the original request URL in a temporary request header invcl_recv and reinstating it upon restart.
  • To ensure that IO draws from the same pre-transform image cache, it's important that shielding is enabled on the primary backend, and that the restart happens on the shield.

Here is an example of how to do this:

Limitations and constraints

Keep the following things in mind when using Image Optimizer.

File size and dimension limits

Image Optimizer enforces the following file size and dimension limits:

  • The maximum input image file size is 50 Megabytes.
  • The maximum input image dimensions are 12,000 x 12,000 pixels.
  • The maximum output image dimensions are 8,192 x 8,192 pixels (8K Ultra HD).
  • The maximum output image area for AVIF images is 4,096 x 4,096 pixels. AVIF is a premium feature of Fastly's Image Optimizer and choosing it as an encoding format will increase your bill. Specific charges will appear on your service order.
  • The maximum output image dimensions for SVG images are 1,600 x 1,600 pixels.
  • The maximum number of frames an animated GIF can contain is 1,000.

Supported image formats

Image Optimizer supports the following image formats:

  • We support input images in AVIF, GIF, HEIC, JPEG, JPEGXL, PNG, or WEBP format. HEIC sequence files are supported, but map to a single frame for the output and do not preserve animation.
  • We can produce output images in AVIF, GIF, JPEG, JPEGXL, MP4, PNG, SVG, or WEBP format.

VCL service requirements

When using Image Optimizer on VCL services, the following requirements apply:

  • Image Optimizer will only process requests that are eligible for caching. If the request passes throughvcl_pass before reaching origin, the response image will not be transformed.
  • Image Optimizer is incompatible with theSegmented Caching feature. If Image Optimizer is enabled, Segmented Caching is disabled automatically.
  • TheVary response header is removed by the Image Optimizer processor automatically aftervcl_fetch execution atshield POPs, so the originalVary response header from origins is not passed to downstream clients including edge POPs. This is to avoid multiple variations of the same original of transformed image being cached individually. We recommend also removing theVary header in your service'svcl_fetch to ensure this behavior is also applied for requests received directly by shield POPs (the relevant VCL is included in ourstandard VCL boilerplate).If you need to satisfyCORS by returning an Origin response header that matches the inbound Origin request header, we recommend adding that header invcl_deliver at the edge POPs. Doing so allows a single cached copy of the response to be reused, while still letting you “customize” the header for different client origins. This approach applies to any request, but for Image Optimizer it is essential, because responses that pass through Image Optimizer cannot have cached variants. For example:
sub vcl_deliver { ... }
Fastly VCL
if (fastly.ff.visits_this_service==0&&resp.http.Access-Control-Allow-Origin) {
setresp.http.Vary:Origin="";
}

Compute platform limitations

When using Image Optimizer on Compute, the following limitations apply:

  • Image Optimizer is available on the Compute platform through our SDKs as part of Fastly'sBeta program. Any request sent to Image Optimizer, including through the SDK, counts as abillable image request for the Image Optimizer product.
  • TheOverlay andMontage features are not supported.
  • Purge works differently on Compute. See thepurging images example.
  • When setting a hostname for the origin request, the hostname or override host defined on the backend is used. If you explicitly set theHost header, it is not passed through.
  • Not all Request methods are respected. For example,set_ttl,set_surrogate_key, andset_stale_while_revalidate are ignored. Cache time defaults to the TTL returned by the origin.
  • Response headers may differ from those returned by VCL services. Origin response headers are preserved, as are headers added by Image Optimizer (such asFastly-Io-Info). However, infrastructure headers likeX-Cache,X-Cache-Hits, andX-Served-By may only reflect the edge server that delivered the response to the end user, rather than showing multiple values from other POPs in the cache path (for example, the shield).
  • In the Rust SDK,Request::send_async andRequest::send_async_streaming are not supported with Image Optimizer.

[8]ページ先頭

©2009-2025 Movatter.jp