A tiny script and component intended to be used with Astro for generating images with eleventy-img.

Overview

Astro + eleventy-img

A tiny script and component intended to be used with Astro for generating images with eleventy-img. It also supports creating blurry placeholders for said images

It was mostly made for my own website and I do not intend to really support this outside of my own needs as more modern and generalist solutions are in the work for Astro

Installation

npm install astro-eleventy-img

Due to an issue in the current version of Vite used by Astro, you need to add the following to your astro project config file:

vite: {
    ssr: {
      external: ["@11ty/eleventy-img"],
    },
},

Usage

The best way to use this in my opinion is to use it to generate images in the public folder. That way, they're copied directly to the result website. This is the default behavior.

Javascript Usage

Generating images

---
import { generateImage } from 'astro-eleventy-img';

const myImage = generateImage('src/assets/my_image.png', {
  // The options here are passed directly to eleventy-img
  widths: [300],
  formats: ['webp', 'avif'],
});
---

<img src={myImage.webp[0].url} />

generateImage returns an object containing all the formats generated and metadata you can use in your HTML, so myImage is equal to:

{
  webp: [
    {
      format: 'webp',
      width: 300,
      height: 240,
      url: '/assets/images/RfSNa8TCUW-300.webp',
      sourceType: 'image/webp',
      srcset: '/assets/images/RfSNa8TCUW-300.webp 300w',
      filename: 'RfSNa8TCUW-300.webp',
      outputPath: 'public/assets/images/RfSNa8TCUW-300.webp'
    }
  ],
  avif: [
    {
      format: 'avif',
      width: 300,
      height: 240,
      url: '/assets/images/RfSNa8TCUW-300.avif',
      sourceType: 'image/avif',
      srcset: '/assets/images/RfSNa8TCUW-300.avif 300w',
      filename: 'RfSNa8TCUW-300.avif',
      outputPath: 'public/assets/images/RfSNa8TCUW-300.avif'
    }
  ]
}

The following files will be generated in the public/assets/images folder:

RfSNa8TCUW-300.webp
RfSNa8TCUW-300.avif

Generating placeholders

---
import { generatePlaceholder } from 'astro-eleventy-img';

const myPlaceholder = generatePlaceholder('src/assets/my_image.png');
---

<img src={myPlaceholder.dataURI} width={myPlaceholder.width} height={myPlaceholder.height} />

generatePlaceholder return an object containing all the properties needed for showing the image. So myPlaceholder in this example is equal to:

{
  dataURI: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAHCAIAAABV+fA3AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAz0lEQVQImQHEADv/AJ7Ho7PYwTt5UhdkNjmLSUOPUCB4MSFzMkGMNACixqksb04WUy4wdz9cnFxPnksbaS0HTCo3hDUAnLmcRnFLQ289ZpZXn7Z9MpA+OYU9EFstVZpHAJ3GaqnPbJXFW5iyZNzLqZWvco+9YHeqVlKXSACu1myt13Cc1GW6ynnFrIjK4ouSzFZ/vlNsskgAytqD1d6Q3+Kevsl/xb951+OXyt6FstVytNRzAIS0S4i2S5u8TK3NXrPOZ57CYqLGXWiqOoi4Rz9UYMGpm241AAAAAElFTkSuQmCC';
  width: 640;
  height: 514;
  quality: 60;
}

Component Usage

Alternatively, it can also be used through a provided component to automatically generate the proper HTML for including the image and its placeholder:

">
---
import { Image } from 'astro-eleventy-img';
---

<Image src="src/assets/my_image.png" alt="My super image!" caption="This is my favorite image." />

will generate the following HTML:

My super image!

This is my favorite image.

">
<figure>
  <picture>
    <source type="image/avif" srcset="/assets/images/4dWK95ygTq-640.avif 640w" />
    <source type="image/webp" srcset="/assets/images/4dWK95ygTq-640.webp 640w" />
    <img
      alt="My super image!"
      loading="lazy"
      decoding="async"
      style="
      background-size: cover;
      background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAHCAIAAABV+fA3AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAz0lEQVQImQHEADv/AJ7Ho7PYwTt5UhdkNjmLSUOPUCB4MSFzMkGMNACixqksb04WUy4wdz9cnFxPnksbaS0HTCo3hDUAnLmcRnFLQ289ZpZXn7Z9MpA+OYU9EFstVZpHAJ3GaqnPbJXFW5iyZNzLqZWvco+9YHeqVlKXSACu1myt13Cc1GW6ynnFrIjK4ouSzFZ/vlNsskgAytqD1d6Q3+Kevsl/xb951+OXyt6FstVytNRzAIS0S4i2S5u8TK3NXrPOZ57CYqLGXWiqOoi4Rz9UYMGpm241AAAAAElFTkSuQmCC);
    "
      onload="this.style.backgroundImage='none'"
      src="/assets/images/4dWK95ygTq-640.png"
      width="640"
      height="514"
    />
  picture>
  <figcaption>
    <p>This is my favorite image.p>
  figcaption>
figure>

and the following files will be generated in the public/assets/images folder:

4dWK95ygTq-640.avif
4dWK95ygTq-640.webp
4dWK95ygTq-640.png

The included Image component is a thin wrapper around generateImage and generatePlaceholder, it works for most needs but do not hesitate to build your own!

Complete Docs available here

Troubleshooting

require is not defined

Make sure to add the following to your astro.config.js config:

vite: {
    ssr: {
      external: ["@11ty/eleventy-img"],
    },
},
You might also like...

Utility for generating preview images of StarCraft: Brood War and Remastered maps

bwpreview Utility for generating preview images of StarCraft: Brood War and Remastered maps (.scm and .scx files). All of the actual work of parsing m

Oct 14, 2022

Piccloud is a full-stack (Angular & Spring Boot) online image clipboard that lets you share images over the internet by generating a unique URL. Others can access the image via this URL.

Piccloud Piccloud is a full-stack application built with Angular & Spring Boot. It is an online image clipboard that lets you share images over the in

Dec 15, 2022

Massive Open-Source Anti-agression Intelligence Collection is intended for civilians to be able to submit and verify intelligence items about an attacking force.

Massive Open-Source Anti-agression Intelligence Collection is intended for civilians to be able to submit and verify intelligence items about an attacking force.

Mar 1, 2022

An action intended to run on pull request and post a comment summarizing any changes to DevCycle variables.

An action intended to run on pull request and post a comment summarizing any changes to DevCycle variables.

Overview With this Github action, information on which DevCycle features have been added or removed in a code change will be shown directly on each Pu

Jun 14, 2022

A simple browser extension, intended to get you "Back To Work" when you start slacking off to one of those really addictive sites.

Back to Work A simple browser extension, intended to get you Back To Work when you start slacking off to one of those really addictive sites. What doe

Nov 19, 2022

Updog is an open-source social media webapp intended to allow everyday people to share their thoughts in a welcoming community.

SE701-Updog Updog is an open-source social media webapp intended to allow everyday people to share their thoughts in a welcoming community. This proje

Apr 18, 2022

A minimal & self-hostable alternative to pastebin intended for code

minBin A minimal & self-hostable alternative to pastebin intended for code Use ⌨️ A public instance is available at https://bin.kio.dev/ Building 🔨 n

Dec 29, 2022

🪆 Template intended to serve as a starting point if you want to bootstrap a Figma Plugin in TypeScript.

🪆 Template intended to serve as a starting point if you want to bootstrap a Figma Plugin in TypeScript.

🪆 Codely Figma Plugin Skeleton Template intended to serve as a starting point if you want to bootstrap a Figma Plugin in TypeScript. Take a look, pla

Dec 22, 2022

Boilerplate / monorepo setup intended for npm package development

Assemble Package Set up: After creating your new repo from the github template plan out what your package(s) will be named and modify the contents of

Dec 15, 2022
Comments
  • relative import of images

    relative import of images

    I don't know if I'm getting this wrong but it's not possible to run this in production, I'm trying to run it as a node middleware,

    
    import { generateImage } from 'astro-eleventy-img';
    
    const myImage = generateImage('src/assets/my_image.png', {
      // The options here are passed directly to eleventy-img
      widths: [300],
      formats: ['webp', 'avif'],
    });
    
    
    <img src={myImage.webp[0].url} />
    

    Here in the docs you clearly import the image as a non-relative file path. While in Astro docs: https://docs.astro.build/en/guides/images/#src

    They state that it should be imported as a relative path.

    In production when we try to generate the image with a non-relative path the image is not found, resulting in the error:

    Lone/dist/server/entry.mjs:8512:5) {
      errno: -4058,
      syscall: 'stat',
      code: 'ENOENT',
      path: './assets/images/Copper1.jpg'
    }
    

    Couldn't figure out a fix I don't know if I have something wrong!

    ofc running this in dev has no problem since we still have access to src.

    opened by DJOCKER-FACE 3
  • Creating new image components

    Creating new image components

    Hi

    Im trying to create a new component so i can pass different options, following your markdownimage example. But im getting an error about the lack of renderers

    Unable to render BackgroundImage!
    
    There are no `renderers` set in your `astro.config.mjs` file.
    

    any tips on this?

    opened by bronze 3
  • Fix merging of placeholder options

    Fix merging of placeholder options

    Hi!

    Thanks for this useful package.

    I noticed that custom placeholder options were not applied (I tried passing { outputDir: "src/assets/placeholders/showcase" }, which did not work).

    To fix this, the order of custom and default options have to be flipped for Object.assign, so that the custom ones take precedence.

    opened by mhyfritz 1
  • Race condition in dev mode

    Race condition in dev mode

    Problem

    Due to the script getting the stats in a sync kind of way while the image is generated asynchronously, sometimes the page will load before the image is done generating which will do a 404 until refresh

    Possible solutions

    We should probably do it fully async? In the past I've encountered issues with that but maybe things are different now

    opened by Princesseuh 1
Owner
Erika
Erika
Examples of using various CSS-in-JS libs in Astro (repo for withastro/astro#4432)

astro + css-in-js This monorepo will show examples of various CSS-in-JS libraries in Astro. Currently only shows a basic counter example, would be nic

Mayank 15 Dec 18, 2022
An Eleventy server plugin to use Browsersync with Eleventy 2.0+.

An Eleventy server plugin to use Browsersync with Eleventy 2.0+.

Eleventy 12 Sep 9, 2022
Easiest 1-click way to install and use Stable Diffusion on your own computer. Provides a browser UI for generating images from text prompts and images. Just enter your text prompt, and see the generated image.

Stable Diffusion UI Easiest way to install and use Stable Diffusion on your own computer. No dependencies or technical knowledge required. 1-click ins

null 3.5k Dec 30, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
MidJourney is an AI text-to-image service that generates images based on textual prompts. It is often used to create artistic or imaginative images, and is available on Discord and through a web interface here.

Midjourney MidJourney is an AI text-to-image service that generates images based on textual prompts. It is often used to create artistic or imaginativ

Andrew Tsegaye 8 May 1, 2023
A frida script that can be used to find the public RSA key used in the native libakamaibmp.so shared library, seen in version 3.3.0 of Akamai BMP

Akamai BMP - RSA/AES Frida Hook This Frida script can be used to find the public RSA key used in the encryption process in Akamai BMP 3.3.0. Since ver

yog 31 Jan 8, 2023
A tiny isomorphic fast function for generating a cryptographically random hex string.

ZeptoID A tiny isomorphic fast function for generating a cryptographically random hex string. Accoding to this calculator one would have to generate i

Fabio Spampinato 9 Oct 24, 2022