3

为网站添加图片 WebP 自动转换功能

 11 months ago
source link: https://dusays.com/635/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

杜老师今天是出差归来,在返京高铁上因为无聊,就看了下近期比较热门的 GitHub 开源项目,正好发现这款工具。可以自动将图片自动转换为 WebP 的格式,同时保持原有的 URL。快点进来了解下吧!

什么是 WebP

WebP 是一种新型图片格式,是由 Google 于 2010 年开发推出。它旨在提供比传统图片格式更高的压缩率,同时保持高质量的图像。

WebP 的优势在于可以在不影响图片质量的情况下显著减小文件大小,从而加快网页加载速度,提高用户体验。

WebP 支持有损和无损压缩,以及动画和透明度。此外,WebP 支持元数据,如 Exif 和 XMP 信息。这使得 WebP 在各种应用场景中都能提供良好性能。

然而,WebP 采用率相对较低,因为它需要较新的浏览器和图像处理库的支持。尽管许多现代浏览器都支持,但一些旧版浏览器和设备可能无法显示 WebP 图像。因此,在部署 WebP 图像时需要考虑到这一点并确保提供适当回退机制。

webp_server_go 是一个基于 Golang 的服务,允许您即时提供 WebP 图像。

webp_server_go 可以将指定目录中的图片自动转换为 WebP 格式,而不更改其 URL。

例如原图为 https://bu.dusays.com/2023/10/12/6527eee969d45.png,新图仍然为 https://bu.dusays.com/2023/10/12/6527eee969d45.png。但后者实际为 WebP 的格式。

webp_server_go 官方介绍支持 JPEG/PNG/BMP/GIF/SVG/HEIC 格式图片文件,实际测试仅 JPEG 格式效果良好。

这里推荐使用 Docker 来部署,docker-compose.yml 的参考内容如下:

version: '3'

services:
webp:
image: webpsh/webp-server-go
# image: ghcr.io/webp-sh/webp_server_go
restart: always
environment:
- MALLOC_ARENA_MAX=1
volumes:
- ./path/to/pics:/opt/pics
- ./exhaust:/opt/exhaust
- ./metadata:/opt/metadata
ports:
- 127.0.0.1:3333:3333

将上方代码中 ./path/to/pics 改为图片所在的路径,如/www/wwwroot/bu.dusays.com./exhaust 为转换后 WebP 图片保存路径,./metadata 为元数据的保存路径。配置好后执行如下命令即可:

docker-compose up -d

如果使用独立域名调用图片,可直接反代 http://127.0.0.1:3333,配置参考下图:

635-1.jpg

如果像杜老师仅处理 JPEG 格式图像,则可以在站点配置文件中添加如下的配置:

location ~* \.(jpg|jpeg)$ 
{
proxy_pass http://127.0.0.1:3333;
proxy_set_header X-Real-IP $remote_addr;
proxy_hide_header X-Powered-By;
proxy_set_header HOST $http_host;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK