Hugo图片自动转webp的方法

由于博客托管在Cloudflare Page上,而cf是出了名的环中国大陆加速,只能想办法从别的方面优化一下博客的加载速度。

我决定先从体积最大的图片入手,优化一下图片的大小,查了一下hugo的文档发现hugo本身有提供对图片进行编辑的.Resize方法。并且hugo允许对MarkDown转html的模板进行修改,于是花了点时间把东西写出来。

博客根目录下创建layouts/_default/_markup/render-image.html文件。

cd {博客根目录}
mkdir -p layouts/_default/_markup
touch layouts/_default/_markup/render-image.html

然后编辑render-image.html文件,粘贴以下内容

<p>
    {{ $image := .Page.Resources.GetMatch .Destination }}
    {{ $text := .Text | default "未命名图片" }}
    {{ if $image }}
    {{ $rawImage := $image }}
    {{ with $rawImage.Exif }}
    {{ if eq .Tags.Orientation 1 }}
    {{ $image := $image.Resize (print $image.Width "x" $image.Height " webp") }}
    {{ else if eq .Tags.Orientation 3 }}
    {{ $image := $image.Resize (print $image.Width "x" $image.Height " webp r180") }}
    {{ else if eq .Tags.Orientation 6 }}
    {{ $image := $image.Resize (print $image.Height "x" $image.Width " webp r270") }}
    {{ else if eq .Tags.Orientation 8 }}
    {{ $image := $image.Resize (print $image.Height "x" $image.Width " webp r90") }}
      <a href="{{ $rawImage.RelPermalink}}" target="view_window">
        <picture>
            <source type="image/webp" srcset="{{ $image.RelPermalink }}">
            <img
                src="{{ $rawImage.RelPermalink }}"
                {{ with $text }}alt="{{ . }}"{{ end }}
                loading="lazy"
        />
        </picture>
      </a>
    {{ end }}
    {{ else }}
    {{ $image := $image.Resize (print $image.Width "x" $image.Height " webp") }}
    <a href="{{ $rawImage.RelPermalink}}" target="view_window">
            <picture>
                <source type="image/webp" srcset="{{ $image.RelPermalink }}">
                <img
                    src="{{ $rawImage.RelPermalink }}"
                    {{ with $text }}alt="{{ . }}"{{ end }}
                    loading="lazy"
            />
            </picture>
        </a>
    {{ end }}
    {{ else }}
    <a href="{{ .Destination | safeURL }}" target="view_window">
        <img
            src="{{ .Destination | safeURL }}"
            {{ with $text }}alt="{{ . }}"{{ end }}
            loading="lazy"
        />
    </a>
    {{ end }}
  </p>

保存后编译网站,这时网站上用![name](path)引入的本地图片就都变成webp格式的了,可以对比一下,图片大小差距很大。

原图大小

原图大小

转换后的大小

转换后的大小

同时现在的图片支持懒加载,并且在不支持webp的浏览器上会使用原图,点击图片还可以查看原图。

2023/11/11更新

支持识别图片EXIF方向,防止转换格式后图片方向改变。

示例图:

EXIF转换实例


最后修改于 2023-07-21