Hugo 图片格式转化及压缩
一。背景说明
目前自己的博客里面空间占用最大的就是图片,一开始自己尽量是把图片格式转化成 webp 格式,图片质量是 10%, 一般的图片质量都是压缩到 80% 左右,但是自己看了下 10% 和 80%,感觉区别不是很大,但是前者空间压缩更极致点。最早图片压缩自己在这个网站上手动上传,压缩后又下载,比较麻烦。所以查阅了官网,Hugo 其实自带一个 Hook,可以做到原生处理,这样就很方便,不用每次额外去处理图片。
二。主要代码
1.目前钩子不是所有地方的图片都能处理,对于你要在博文里面展示,并且希望能够自动处理的图片,它有路径的限制,比如 static/ 下面的就处理不了。要求把图片放博客文章的同级目录里,比如 index.md 是文章主题内容,在同级目录下,放你要处理的图片,如:my-image.jpg。
content/
└── posts/
└── my-post/
├── index.md
└── my-image.jpg
2.新建 render-image.html 文件。
路径:themes\hugo-bearblog-neo\layouts\_default\_markup\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 (printf "%dx%d webp q10" $image.Width $image.Height) }}
{{ else if eq .Tags.Orientation 3 }}
{{ $image := $image.Resize (printf "%dx%d webp q10 r180" $image.Width $image.Height) }}
{{ else if eq .Tags.Orientation 6 }}
{{ $image := $image.Resize (printf "%dx%d webp q10 r270" $image.Height $image.Width) }}
{{ else if eq .Tags.Orientation 8 }}
{{ $image := $image.Resize (printf "%dx%d webp q10 r90" $image.Height $image.Width) }}
<figure>
<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>
<figcaption class="image-caption">{{ $text }}</figcaption>
</figure>
{{ end }}
{{ else }}
{{ $image := $image.Resize (printf "%dx%d webp q10" $image.Width $image.Height) }}
<figure>
<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>
<figcaption class="image-caption">{{ $text }}</figcaption>
</figure>
{{ end }}
{{ else }}
<figure>
<a href="{{ .Destination | safeURL }}" target="view_window">
<img
src="{{ .Destination | safeURL }}"
{{ with $text }}alt="{{ . }}"{{ end }}
loading="lazy"
/>
</a>
<figcaption class="image-caption">{{ $text }}</figcaption>
</figure>
{{ end }}
</p>
三。结果展示
五。后续问题
实际按照这个方法处理后,确实少了自己处理图片这一步,但是当实际图片多起来时,Hugo 第一次编译时间会很长,处理后的图片可以在 resources 目录下看到,图片处理的时间一长,就会连带出现其他错误,就比如自己目前在用的这个主题,会导致 SEO 标签生成也超时,导致项目部署失败。最终自己决定图片转化这一步还是不交给 Hugo 处理,可以通过 python 等其他脚本处理,不丢失原有 Hguo 编译项目快的优势。