Use picture tag with Image processing

I want to add for my webpage several images with picture tag.
I want it to look something like this:

 <picture>
 <source srcset="img/image-320.webp 320w, img/image-640.webp 640w, img/image-960.webp 960w"  type="image/webp">
 <source srcset="img/image-320.jpg 320w, img/image-640.jpg 640w, img/image-960.jpg 960w"  type="image/jpg ">
 <img src="img/image-960.jpg" width="960" height="960" alt="Image alt text">
 </picture>

I am trying to connect it with Image processing.
My current shortcode:

{{ $original := .Page.Resources.GetMatch (printf "*%s*" (.Get 0)) }}
{{ $command := .Get 1 }}
{{ $options := .Get 2 }}
{{ $classes := .Get 3 }}

{{ if eq $command "Fit"}}
{{ .Scratch.Set "image" ($original.Fit $options) }}
{{ else if eq $command "Resize"}}
{{ .Scratch.Set "image" ($original.Resize $options) }}
{{ else if eq $command "Fill"}}
{{ .Scratch.Set "image" ($original.Fill $options) }}
{{ else }}
{{ errorf "Invalid image processing command: Must be one of Fit, Fill or Resize."}}
{{ end }}
{{ $image := .Scratch.Get "image" }}

<div class="image {{ $classes }}">
	<picture>
		<source srcset="{{ $image.RelPermalink }}" type="image/webp">
		<img src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}">	
	</picture>
</div>

Shortcode in md file:

{{< picture image Resize "960x q100 webp" image--test>}}

And result:

<div class="image image--test">
	<picture>
		<source srcset="/picture/image_hue851aec3dc2c3aacbe412b4b2948fb92_39442_960x0_resize_q100_h2_box.webp" type="image/webp">
		<img src="/picture/image_hue851aec3dc2c3aacbe412b4b2948fb92_39442_960x0_resize_q100_h2_box.webp" width="960" height="960">	
	</picture>
</div>

I need next things:

  • Fallback image have to be .jpg;
  • I want to cropp img for severel options (320, 640, 960);
  • Fill and Fit features do not work (It would be cool if it worked)

Does anyone know how to implement this?

If you ever decide to use the Cloudinary free tier and simply let Cloudinary serve the format automatically — in which case you wouldn’t need picture — you could try something like what I wrote about here:

1 Like