- Stable
3.0.0
Toggle Menu
1.93s
22.90s
Image
Low level utility to perform build-time image transformations for both vector and raster images. Output multiple sizes, save multiple formats, cache remote images locally.
- Uses the sharp image processor.
eleventy-img
on GitHub
You maintain full control of markup. Use with <picture>
, <img>
, CSS background-image
, or others!
- Easily add
width
andheight
attributes on<img>
elements for proper aspect ratio to reduce layout shift. - Accepts a variety of image types as input:
jpeg
,png
,webp
,gif
,tiff
,avif
, andsvg
.- Does not rely on file extensions (like
.png
or.jpg
) in URLs or local files, which may be missing or inaccurate.
- Does not rely on file extensions (like
- Output multiple sizes, maintaining the original aspect ratio.
- Never upscales raster images larger than original size (with the option to upscale SVG input).
- Output multiple formats, supports:
jpeg
,png
,webp
,avif
+1
Build Cost, andsvg
(SVG output requires SVG input) - Fast: de-duplicates image requests with both an in-memory and disk cache. During local development, images are processed on request for even faster build performance.
- Robust: Save remote images locally to prevent broken image URLs (via
eleventy-fetch
).
Installation
Published as @11ty/eleventy-img
on npm.
npm install @11ty/eleventy-img
Usage
This example is the lowest-level use of Eleventy Image and returns a promise. This usage works independent of Eleventy.
import Image from "@11ty/eleventy-img";
let src = "https://images.unsplash.com/photo-1608178398319-48f814d0750c";
let stats = await Image(src, {
widths: [300],
});
console.log(stats);
const Image = require("@11ty/eleventy-img");
// ESM is required for top level async/await.
(async () => {
let src = "https://images.unsplash.com/photo-1608178398319-48f814d0750c";
let stats = await Image(src, {
widths: [300],
});
console.log(stats);
})();
Three things happen here:
- (Optional) If the first argument is a full URL (not a local file path), we download the remote image and cache it locally using the Fetch plugin. This cached original is then used for the cache duration to avoid a bunch of network requests.
- Images are then created for each format and width from the input source. In this example, two files are created:
./img/6dfd7ac6-300.webp
and./img/6dfd7ac6-300.jpeg
. - The promise resolves with a metadata object describing those newly created optimized images.
Expand to see a sample returned metadata object
{
webp: [
{
format: 'webp',
width: 300,
height: 300,
filename: '6dfd7ac6-300.webp',
outputPath: 'img/6dfd7ac6-300.webp',
url: '/img/6dfd7ac6-300.webp',
sourceType: 'image/webp',
srcset: '/img/6dfd7ac6-300.webp 300w',
size: 10184
}
],
jpeg: [
{
format: 'jpeg',
width: 300,
height: 300,
filename: '6dfd7ac6-300.jpeg',
outputPath: 'img/6dfd7ac6-300.jpeg',
url: '/img/6dfd7ac6-300.jpeg',
sourceType: 'image/jpeg',
srcset: '/img/6dfd7ac6-300.jpeg 300w',
size: 15616
}
]
}
Output Widths
Controls how many output images will be created for each image format. Aspect ratio is preserved.
widths: ["auto"]
(default, keep original width)"auto"
.widths: [200]
(output one 200px width)widths: [200, "auto"]
(output 200px and original width)
Output Formats
Use almost any combination of these:
formats: ["webp", "jpeg"]
(default)formats: ["png"]
formats: ["auto"]
(keep original format)"auto"
formats: ["svg"]
(requires SVG input)formats: ["avif"]
+1
Build Cost
Output Locations
URL Path
A path-prefix-esque directory for the <img src>
attribute. e.g. /img/
for <img src="/img/MY_IMAGE.jpeg">
:
urlPath: "/img/"
(default)
Output Directory
Where to write the new images to disk. Project-relative path to the output image directory. Maybe you want to write these to your output directory directly (e.g. ./_site/img/
)?
outputDir: "./img/"
(default)
Options for SVG
Skip raster formats for SVG
If using SVG output (the input format is SVG and svg
is added to your formats
array), we will skip all of the raster formats even if theyβre in formats
. This may be useful in a CMS-driven workflow when the input could be vector or raster.
svgShortCircuit: false
(default)svgShortCircuit: true
svgShortCircuit: "size"
Added in Image v3.1.8
Using svgShortCircuit: "size"
means that raster image format entries will only be thrown out if the optimized raster size is larger than the SVG. This helps with large SVG images that compress to smaller raster sizes at smaller widths and will prefer the SVG over raster formats when the SVG file size is smaller.
To use Brotli compressed SVG sizes when making file size comparisons, use the svgCompressionSize: "br"
option Added in Image v3.1.8.
Related:
Allow SVG to upscale
While we do prevent raster images from upscaling (and filter upscaling widths
from the output), you can optionally enable SVG input to upscale to larger sizes when converting to raster format.
svgAllowUpscale: true
(default)svgAllowUpscale: false
Use this in your templates
There are four different ways to use Eleventy Image in Eleventy projects:
- Eleventy Transform (Recommended. Easiest to configure, works with all template types)
- Asynchronous Shortcode (Nunjucks, Liquid, 11ty.js)
- WebC Component
- Synchronous Shortcode (Deprecated)
Eleventy Transform
Added in v3.0.0 Added in Image v4.0.1This is the easiest method to configure. You add a bit of code to your configuration file and weβll transform any <img>
tags in HTML files that exist in your output folder (probably _site/**/*.html
).
Added in v3.0.0Added in Image v5.0.0During local development (when using --serve
), images optimized via transform are not processed at build time and instead are optimized when requested in the browser. Read more about transformOnRequest
.
import { eleventyImageTransformPlugin } from "@11ty/eleventy-img";
export default function (eleventyConfig) {
eleventyConfig.addPlugin(eleventyImageTransformPlugin, {
// which file extensions to process
extensions: "html",
// Add any other Image utility options here:
// optional, output image formats
formats: ["webp", "jpeg"],
// formats: ["auto"],
// optional, output image widths
// widths: ["auto"],
// optional, attributes assigned on <img> override these values.
defaultAttributes: {
loading: "lazy",
decoding: "async",
},
});
};
const { eleventyImageTransformPlugin } = require("@11ty/eleventy-img");
module.exports = function (eleventyConfig) {
eleventyConfig.addPlugin(eleventyImageTransformPlugin, {
// which file extensions to process
extensions: "html",
// Add any other Image utility options here:
// optional, output image formats
formats: ["webp", "jpeg"],
// formats: ["auto"],
// optional, output image widths
// widths: ["auto"],
// optional, attributes assigned on <img> override these values.
defaultAttributes: {
loading: "lazy",
decoding: "async",
},
});
};
Relative paths
If you do not specify the urlPath
option:
- Relative image sources (
<img src="./possum.png">
) will be co-located in your output directory with the template they are used in. Note that if the same source image is used in multiple templates, it will be written to two different locations! - Absolute image sources (
<img src="/possum.png">
) will be normalized relative to your input/content directory and written to your output directory with the default directory (e.g._site/img/
).
Attribute overrides
You can configure individual <img>
elements with per-instance overrides:
<img eleventy:ignore>
skips this image.<img eleventy:formats="webp">
comma separated string to override the default formats.<img eleventy:widths="200,600">
comma separated string to override the default widths.<img eleventy:output>
overrides the output directory. Similar tourlPath
above, absolute paths (e.g.<img eleventy:output="/mydirectory/">
) are relative to the Eleventy output directory and relative paths are relative to the templateβs URL (e.g.<img eleventy:output="./mydirectory/">
).
eleventy:ignore
to the <img>
attributes so the images arenβt optimized twice (e.g. Image.generateHTML(metadata, { "eleventy:ignore": "" });
).Nunjucks, Liquid, JavaScript (Asynchronous Shortcodes)
The examples below require an async-friendly shortcodes (works in Nunjucks, Liquid, JavaScript, and WebC).
import Image from "@11ty/eleventy-img";
export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt, widths = [300, 600], sizes = "100vh") {
let metadata = await Image(src, {
widths,
formats: ["avif", "jpeg"],
});
let imageAttributes = {
alt,
sizes,
loading: "lazy",
decoding: "async",
};
// You bet we throw an error on a missing alt (alt="" works okay)
return Image.generateHTML(metadata, imageAttributes);
});
};
const Image = require("@11ty/eleventy-img");
module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt, widths = [300, 600], sizes = "100vh") {
let metadata = await Image(src, {
widths,
formats: ["avif", "jpeg"],
});
let imageAttributes = {
alt,
sizes,
loading: "lazy",
decoding: "async",
};
// You bet we throw an error on a missing alt (alt="" works okay)
return Image.generateHTML(metadata, imageAttributes);
});
};
Expand to see full options list for Image.generateHTML
import Image from "@11ty/eleventy-img";
export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt, widths = ["auto"], sizes = "100vh") {
let metadata = await Image(src, {
// omitted for brevity
});
let imageAttributes = {
// omitted for brevity
};
let options = {
// HTML attributes added to `<picture>` (left out if <img> is used)
// Added in v4.0.0
pictureAttributes: {},
// Condense HTML output to one line (no new lines)
// Added in v0.7.3
whitespaceMode: "inline", // or: "block"
};
// You bet we throw an error on a missing alt (alt="" works okay)
// Note that `options` are *optional*
return Image.generateHTML(metadata, imageAttributes, options);
});
};
const Image = require("@11ty/eleventy-img");
module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt, widths = ["auto"], sizes = "100vh") {
let metadata = await Image(src, {
// omitted for brevity
});
let imageAttributes = {
// omitted for brevity
};
let options = {
// HTML attributes added to `<picture>` (left out if <img> is used)
// Added in v4.0.0
pictureAttributes: {},
// Condense HTML output to one line (no new lines)
// Added in v0.7.3
whitespaceMode: "inline", // or: "block"
};
// You bet we throw an error on a missing alt (alt="" works okay)
// Note that `options` are *optional*
return Image.generateHTML(metadata, imageAttributes, options);
});
};
The addShortcode
method is async-friendly in Eleventy 2.0+. Use addAsyncShortcode
in older versions of Eleventy. You can also add these shortcodes to individual template engines, if youβd like!
If you want to use Eleventy Image in WebC, take note that it is possible to wire up the method below in WebC. However it is recommended to use the provided <eleventy-image>
WebC component instead.
Now you can use the image
shortcode in your templates and the appropriate HTML will be generated for you (based on your specified Image options).
{% image "cat.jpg", "photo of my tabby cat" %}
{% image "cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw" %}
The comma between arguments is optional in Liquid templates.
{% image "cat.jpg", "photo of my tabby cat" %}
{% image "cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw" %}
The comma between arguments is required in Nunjucks templates.
export default function() {
let img1 = await this.image("cat.jpg", "photo of my tabby cat");
let img2 = await this.image("cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw");
return `${img1}
${img2}`;
};
module.exports = function() {
let img1 = await this.image("cat.jpg", "photo of my tabby cat");
let img2 = await this.image("cat.jpg", "photo of my tabby cat", "(min-width: 30em) 50vw, 100vw");
return `${img1}
${img2}`;
};
Synchronous Shortcode
Expand to see an example of Synchronous usage.
Use Image.statsSync
to get the metadata of a source even if the image generation is not finished yet:
import Image from "@11ty/eleventy-img";
function imageShortcode(src, cls, alt, widths = ["auto"], sizes = "100vh") {
let options = {
widths,
formats: ["jpeg"],
};
// generate images, while this is async we donβt wait
Image(src, options);
let imageAttributes = {
class: cls,
alt,
sizes,
loading: "lazy",
decoding: "async",
};
// get metadata even if the images are not fully generated yet
let metadata = Image.statsSync(src, options);
return Image.generateHTML(metadata, imageAttributes);
}
export default function (eleventyConfig) {
eleventyConfig.addShortcode("myImage", imageShortcode);
};
const Image = require("@11ty/eleventy-img");
function imageShortcode(src, cls, alt, widths = ["auto"], sizes = "100vh") {
let options = {
widths,
formats: ["jpeg"],
};
// generate images, while this is async we donβt wait
Image(src, options);
let imageAttributes = {
class: cls,
alt,
sizes,
loading: "lazy",
decoding: "async",
};
// get metadata even if the images are not fully generated yet
let metadata = Image.statsSync(src, options);
return Image.generateHTML(metadata, imageAttributes);
}
module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("myImage", imageShortcode);
};
WebC
Added in Image v3.1.0 Eleventy Image now provides a built-in <eleventy-image>
WebC component for use in your Eleventy project.
Using Eleventy Image in WebC offers all the same great benefits youβre used to from Eleventy Image with an intuitive declarative HTML-only developer experience. WebC components work in *.webc
files. For similar functionality in other template formats, use the the Liquid/Nunjucks/JavaScript shortcodes above (or even <eleventy-image>
with the Render plugin).
First, add the following to your projectβs configuration file:
import eleventyWebcPlugin from "@11ty/eleventy-plugin-webc";
import { eleventyImagePlugin } from "@11ty/eleventy-img";
export default function (eleventyConfig) {
// WebC
eleventyConfig.addPlugin(eleventyWebcPlugin, {
components: [
// β¦
// Add as a global WebC component
"npm:@11ty/eleventy-img/*.webc",
],
});
// Image plugin
eleventyConfig.addPlugin(eleventyImagePlugin, {
// Set global default options
formats: ["webp", "jpeg"],
urlPath: "/img/",
// Notably `outputDir` is resolved automatically
// to the project output directory
defaultAttributes: {
loading: "lazy",
decoding: "async",
},
});
};
const eleventyWebcPlugin = require("@11ty/eleventy-plugin-webc");
const { eleventyImagePlugin } = require("@11ty/eleventy-img");
module.exports = function (eleventyConfig) {
// WebC
eleventyConfig.addPlugin(eleventyWebcPlugin, {
components: [
// β¦
// Add as a global WebC component
"npm:@11ty/eleventy-img/*.webc",
],
});
// Image plugin
eleventyConfig.addPlugin(eleventyImagePlugin, {
// Set global default options
formats: ["webp", "jpeg"],
urlPath: "/img/",
// Notably `outputDir` is resolved automatically
// to the project output directory
defaultAttributes: {
loading: "lazy",
decoding: "async",
},
});
};
Added in v3.0.0Added in Image v5.0.0During local development (when using --serve
), <eleventy-image>
images are not processed at build time and instead are optimized when requested in the browser. Read more about transformOnRequest
.
Now you can use the <eleventy-image>
WebC component in your templates.
Expand to see Eleventy Image WebC component Examples
<img webc:is="eleventy-image" src="cat.jpg" alt="photo of my tabby cat" />
<eleventy-image src="cat.jpg" alt="photo of my tabby cat"></eleventy-image>
<!-- Specify widths: -->
<img
webc:is="eleventy-image"
width="100, 200"
src="cat.jpg"
alt="photo of my tabby cat"
/>
<img
webc:is="eleventy-image"
:width="[100, 200]"
src="cat.jpg"
alt="photo of my tabby cat"
/>
<!-- Specify formats (overriding defaults set via the configuration) -->
<img
webc:is="eleventy-image"
formats="avif, png"
src="cat.jpg"
alt="photo of my tabby cat"
/>
<img
webc:is="eleventy-image"
:formats="['avif', 'png']"
src="cat.jpg"
alt="photo of my tabby cat"
/>
<!-- Change the url path or output dir (overriding defaults set via the configuration above) -->
<img
webc:is="eleventy-image"
url-path="/some-dir/"
output-dir="_site/some-dir/"
src="cat.jpg"
alt="photo of my tabby cat"
/>
Build Cost π§°
Image optimization is likely one of the costlier pieces of your Eleventy build. The total build cost of this utility is dependent on a few things:
- Number of unique images optimized (not number of pages)
- Number of
widths
you generate for each source image. - Number of
formats
you generate for each source image.avif
is more costly than other image formats.+1
Build Cost
- File size of images being optimized (larger source images are more expensive).
- Optimizing a lot of remote images (image content must be fetched from a remote server and is subsequently cached via
eleventy-fetch
).
Optimize Images on Request
Added in v3.0.0Added in Image v5.0.0When using the transform method or the WebC component, image processing is removed from the build for extra performance. Instead, they are processed when requested by the browser using a special middleware built-in to the Eleventy Dev Server. This is enabled or disabled using the transformOnRequest
option.
transformOnRequest: false
(default)transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve"
(default for Transform method and WebC)
Optimize On Request with Shortcodes
Added in v3.0.0Added in Image v5.0.0You can use this with the Eleventy Shortcode directly too, with a little bit more configuration:
import Image from "@11ty/eleventy-img";
import { eleventyImageOnRequestDuringServePlugin } from "@11ty/eleventy-img";
export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let metadata = await Image(src, {
transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve"
});
// You bet we throw an error on a missing alt (alt="" works okay)
return Image.generateHTML(metadata, imageAttributes);
});
// Add the dev server middleware manually
eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin);
};
const Image = require("@11ty/eleventy-img");
const { eleventyImageOnRequestDuringServePlugin } = require("@11ty/eleventy-img");
module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
let metadata = await Image(src, {
transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve"
});
// You bet we throw an error on a missing alt (alt="" works okay)
return Image.generateHTML(metadata, imageAttributes);
});
// Add the dev server middleware manually
eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin);
};
In-Memory Cache
To prevent duplicate work and improve build performance, repeated calls to the same source image (remote or local) with the same options will return a cached results object. If a request in-progress, the pending promise will be returned. This in-memory cache is maintained across builds in watch/serve mode. If you quit Eleventy, the in-memory cache will be lost.
Images will be regenerated (and the cache ignored) if:
- The source image file size changes (on local image files)
- The cache asset duration expires (for remote images).
You can disable this behavior by using the useCache
boolean option:
useCache: true
(default)useCache: false
to bypass the cache and generate a new image every time.
Examples
Example of in-memory cache reuse (returns the same promise)
import Image from "@11ty/eleventy-img";
let stats1 = Image("./test/bio-2017.jpg");
let stats2 = Image("./test/bio-2017.jpg");
console.assert(stats1 === stats2, "The same promise");
Example of in-memory cache (returns a new promise with different options)
import Image from "@11ty/eleventy-img";
let stats1 = Image("./test/bio-2017.jpg");
let stats2 = Image("./test/bio-2017.jpg", { widths: [300] });
console.assert(stats1 !== stats2, "A different promise");
Disk Cache
Added in Image v1.0.0 Eleventy will skip processing files that are unchanged and already exist in the output directory. This requires the built-in hashing algorithm and is not yet supported with custom filenames. More background at Issue #51.
You can use this to speed up builds on your build server.
Advanced Usage
Fix Orientation
Added in Image v4.0.0Rotates the image to enforce the correct orientation set in EXIF metadata.
fixOrientation: false
(default)fixOrientation: true
Custom Filenames
Donβt like those hash ids? Make your own!
// (some configuration truncatedβ¦)
// Define custom filenames for generated images
filenameFormat: function (id, src, width, format, options) {
// id: hash of the original image
// src: original image path
// width: current width in px
// format: current file format
// options: set of options passed to the Image call
return `${id}-${width}.${format}`;
}
Custom Filename Example: Use the original file slug
import path from "node:path";
import Image from "@11ty/eleventy-img";
await Image("./test/bio-2017.jpg", {
widths: [300],
formats: ["auto"],
filenameFormat: function (id, src, width, format, options) {
const extension = path.extname(src);
const name = path.basename(src, extension);
return `${name}-${width}w.${format}`;
},
});
// Writes: "test/img/bio-2017-300w.jpeg"
Dry-Run
If you want to try the utility out and not write any files (useful for testing), use the dryRun
option.
dryRun: false
(default)dryRun: true
Make your own Markup
If you have an advanced use case and donβt want to use our methods to generate the image markup, you can do it yourself!
import Image from "@11ty/eleventy-img";
export default function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
if (alt === undefined) {
// You bet we throw an error on missing alt (alt="" works okay)
throw new Error(`Missing \`alt\` on myImage from: ${src}`);
}
let metadata = await Image(src, {
widths: [600],
formats: ["jpeg"],
});
let data = metadata.jpeg[metadata.jpeg.length - 1];
return `<img src="${data.url}" width="${data.width}" height="${data.height}" alt="${alt}" loading="lazy" decoding="async">`;
});
};
const Image = require("@11ty/eleventy-img");
module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode("image", async function (src, alt) {
if (alt === undefined) {
// You bet we throw an error on missing alt (alt="" works okay)
throw new Error(`Missing \`alt\` on myImage from: ${src}`);
}
let metadata = await Image(src, {
widths: [600],
formats: ["jpeg"],
});
let data = metadata.jpeg[metadata.jpeg.length - 1];
return `<img src="${data.url}" width="${data.width}" height="${data.height}" alt="${alt}" loading="lazy" decoding="async">`;
});
};
Process images as a Custom Template
Use Eleventyβs Custom Template Language feature to process images. This one is not yet available on the docs: do you want to contribute it?
Process images as Data Files
Added in v2.0.0 Nontraditional use case. Eleventyβs Custom Data File Formats features an example of processing Images as data files to feed EXIF data into the Data Cascade. You can use the same feature to add the metadata stats returned from the Image utility directly to the Data Cascade for use in your templates.
- Benefits:
- Processing happens in the data cascade so this works in any template language.
- Images stored in the global data folder will be processed and available to all templates
- Drawbacks:
- You canβt customize the Image options (e.g.
widths
orformats
) from the template code. It is set globally in the config.
- You canβt customize the Image options (e.g.
- Both a benefit and a drawback:
- Beholden to Eleventyβs Data Cascade file name conventions when using with template/directory data files.
Show the code
import path from "node:path";
import Image from "@11ty/eleventy-img";
export default function (eleventyConfig) {
eleventyConfig.addDataExtension("png,jpeg", {
read: false, // Donβt read the input file, argument is now a file path
parser: async (imagePath) => {
let stats = await Image(imagePath, {
widths: ["auto"],
formats: ["avif", "webp", "jpeg"],
outputDir: path.join(eleventyConfig.dir.output, "img", "built"),
});
return {
image: {
stats,
},
};
},
});
// This works sync or async: images were processed ahead of time in the data cascade
eleventyConfig.addShortcode("dataCascadeImage", (stats, alt, sizes) => {
let imageAttributes = {
alt,
sizes,
loading: "lazy",
decoding: "async",
};
return Image.generateHTML(stats, imageAttributes);
});
};
const path = require("node:path");
const Image = require("@11ty/eleventy-img");
module.exports = function (eleventyConfig) {
eleventyConfig.addDataExtension("png,jpeg", {
read: false, // Donβt read the input file, argument is now a file path
parser: async (imagePath) => {
let stats = await Image(imagePath, {
widths: ["auto"],
formats: ["avif", "webp", "jpeg"],
outputDir: path.join(eleventyConfig.dir.output, "img", "built"),
});
return {
image: {
stats,
},
};
},
});
// This works sync or async: images were processed ahead of time in the data cascade
eleventyConfig.addShortcode("dataCascadeImage", (stats, alt, sizes) => {
let imageAttributes = {
alt,
sizes,
loading: "lazy",
decoding: "async",
};
return Image.generateHTML(stats, imageAttributes);
});
};
With a template my-blog-post.md
and an image file my-blog-post.jpeg
, you could use the above configuration code in your template like this:
{% dataCascadeImage image.stats, "My alt text" %}
Note this also means that folder/folder.jpeg
would be processed for all templates in folder/*
and any images stored in your global _data
would also be populated into the data cascade based on their folder structure.
Change Global Plugin Concurrency
import Image from "@11ty/eleventy-img";
Image.concurrency = 4; // default is 10
Advanced control of Sharp image processor
Extra options to pass to the Sharp constructor or the Sharp image format converter for webp, png, jpeg, or avif.
sharpOptions: {}
sharpWebpOptions: {}
sharpPngOptions: {}
sharpJpegOptions: {}
sharpAvifOptions: {}
Output Animated GIF or WebP
Added in Image v1.1.0 To process and output animated gif
or webp
images, use the animated
option for the Sharp constructor.
import Image from "@11ty/eleventy-img";
await Image("./test/bio-2017.jpg", {
formats: ["webp", "gif"],
sharpOptions: {
animated: true,
},
});
Change the default Hash length
You can customize the length of the default filename format hash by using the hashLength
property.
import Image from "@11ty/eleventy-img";
await Image("./test/bio-2017.jpg", {
hashLength: 8, // careful, donβt make it _too_ short!
});
Advanced Caching Options for Remote Images
For any full URL first argument to this plugin, the full-size remote image will be downloaded and cached locally. See all relevant eleventy-fetch
options.
{
cacheOptions: {
// if a remote image URL, this is the amount of time before it fetches a fresh copy
duration: "1d",
// project-relative path to the cache directory
directory: ".cache",
removeUrlQueryParams: false,
},
}
When caching remote images, you may want to check the processed image output into your git
(et al) repository to avoid refetches in the future. If remote images are not checked in, they may be refetched every time on your CI server unless you preserve the .cache
folder between builds.
Using a Hosted Image Service
Custom URLs
Want to use a hosted image service instead? You can override the entire URL. Takes precedence over filenameFormat
option. Useful with statsSync
or statsByDimensionsSync
.
The metadata object returned will not include filename
or outputPath
properties.
{
urlFormat: function ({
hash, // not included for `statsOnly` images
src,
width,
format,
}) {
return `https://example.com/${encodeURIComponent(src)}/${width}/${format}/`;
}
}
Stats Only
Added in Image v1.1.0 Skips all image processing to return metadata. Doesnβt read files, doesnβt write files. Use this as an alternative to the separate statsSync*
functionsβthis will use in-memory cache and de-duplicate requests.
statsOnly: false
(default)statsOnly: true
For versions prior to Image 5.0, you need to supply the dimensions when using statsOnly
via remoteImageMetadata
:
{
statsOnly: true,
// Not required in Image 5.0+
remoteImageMetadata: {
width,
height,
format, // optional
}
}
From the Community
Γ90 resources via 11tybundle.dev curated by Bob Monsour.