Create an image sprite from images in the assets directory

Hello everyone,
It could be good to be able to create sprites with the image post processor. Indeed, css sprites help to avoid many requests for small images and increase performance. I am not knowledgeable enough (and unfortunately no time to learn) to propose an implementation. So please can someone implement this feature ?

I’m not sure how practical it is, but it should be possible to create sprites with

1 Like

Hello,
Thanks for the answer. In fact, the purpose is not to overlay one image, but to create the sprite from several images having /resized to the same size at post processing phase such that one can use the css to select the one we want. Let me give an example : i have a list of partners, let say 10, each of them have logos, I created (manually) an image containing the 10 logos and select the appropriate one from the background-position style (a kind of crop). Doing like this, I only have one request for the image instead of 10. This also applies to icons we use. Thus what could be interesting is to do it with the image processor and in the very spirit of Hugo. The sprites trick is an advice coming from google lighthouse analysis tool and was largely used before.

If you overlay 10 images onto a blank image you have a sprite. But I understand that this is hard to do from the templates and that you want something … automatic.

1 Like

no, that’s fine with small images in a blank image, i’ll try it. thanks.

Take this for a spin:

git clone --single-branch -b hugo-forum-topic-52305 https://github.com/jmooring/hugo-testing hugo-forum-topic-52305
cd hugo-forum-topic-52305
hugo server

Usage

1) Place the images to include in the sprite somewhere in the assets directory, or in a directory mounted to the assets directory:

assets/
└── images/
    └── partners/
        └── logos/
            β”œβ”€β”€ a.jpg
            └── b.jpg

2) Place this within the head element of your base template:

{{ $opts := dict "directory" "images/partners/logos" }}
{{ partialCached "make-sprite.html" $opts }}

3) Use the sprite in your templates. For example:

<div id="a"></div>
<div id="b"></div>

Notes

Run this command to see the site’s published structure:

rm -rf public && hugo && tree public

You can call the partial multiple times, passing a different directory in each call, and optionally add a namespace parameter to categorize sprites (e.g., one sprite for logos, another sprite for symbols, etc.).

See comments in layouts/partials/make-sprite.html for options.

This approach uses two image filters: padding and overlay.

3 Likes

waouh ! This is a exactly the solution I need. Thank you so much for spending your time to help me.

2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.