skip to content
Logo 三七の小站

CF worker 图片压缩

/ 5 min read

官方文档

https://developers.cloudflare.com/images/cloudflare-images/transformations/

0. 功能说明

已知图片链接 https://images.com/hh4sv.jpg

但是觉得图片太大, 加载太慢, 想压缩小一点, 在不怎么损失画质的前提下, 大大减少图片体积

只需在链接前加上一个托管到cf的域名, 假如是 image.111111.xyz

可以直接将 ![](https://image.111111.xyz/https://images.com/hh4sv.jpg)

放在文章段落中 ,显示的就是压缩之后的图片了

这和 webp.se 功能类似 (没用过, 我不知道webp.se能不能压缩成avif格式, 经过我的测试, Cloudflare可以, 因为压缩成avif很吃资源, 本地台式机都要5-10s, 还是有点折腾的意义的)

原图:

https://images.bilibili.quest/i/2024/10/25/iip4t.jpg

压缩后

1. 开启图像转换

打开Cloudflare控制台, Images -> 转换 -> 对应域名 -> 启用

2. 添加一条DNS

在域名的 DNS 记录中添加一条 CNAME 记录 : image.11111.xyz -> visa.com

取消小黄云

3. 创建一个worker

创建一个worker ,然后编辑代码, 复制下面这一段进去

参数可以不动, 也可以自己调整, 但是必须修改example.com那一块!!!

/**
* Fetch and log a request
* @param {Request} request - The incoming request object containing all information about the HTTP request.
*/
export default {
async fetch(request) {
let url = new URL(request.url); // 解析请求URL以获取路径信息
const imageURL = url.pathname.substring(1); // 去除第一个`/`, 从路径中提取图像URL
if (!imageURL) return new Response('缺少图像路径', { status: 400 });
// 定义参数
let options = {
cf: {
image: {
quality: 90, //质量 (60 - 90, 越低体积越小, 质量越差)
format: "avif" , //格式 avif webp ( avif 效果最好, 但是如果原图分辨率太高则无法触发 )
fit: "scale-down", // 当图片分辨率过大时, 缩小到下面的宽高
width: 1776, // 经过我的测试, 设置为1776能稳定触发avif格式压缩 ( avif压缩很费资源 )
height: 1776
} } };
if (!imageURL) return new Response('缺少 "image" 参数值', { status: 400 }); // 如果没有提供图像URL,则返回400错误
try {
const { hostname, pathname } = new URL(imageURL); // 从图片地址提取主机名和路径名
// 仅允许具有JPEG、PNG、GIF或WebP文件扩展名的URL
if (!/\.(jpe?g|png|gif|webp)$/i.test(pathname)) {
return new Response('不允许的文件扩展名', { status: 400 }); // 如果文件扩展名不在允许列表内,则返回400错误
}
// 示例:仅接受来自 "example.com" 的图像
// 添加第二个网站则在if里面添加: && hostname !== 'another-example.com'
if (hostname !== 'example.com') {
// 如果主机名不是"example.com",则返回403错误
return new Response('必须使用 "example.com" 作为源图像', { status: 403 });
}
} catch (err) {
return new Response('无效的图片地址参数值', { status: 400 }); // 如果解析URL出错,则返回400错误
}
const imageRequest = new Request(imageURL, {
headers: request.headers
});
return fetch(imageRequest, options);
}}

修改上面的example.com, 为你自己的图床网址, 如果希望解除限制则注释或删除这一段

if (hostname !== 'example.com') {
// 如果主机名不是"example.com",则返回403错误
return new Response('必须使用 "example.com" 作为源图像', { status: 403 });
}

3. 添加路由

添加一条路由, 格式为: image.111111.xyz/*

完成, 现在可以在浏览器中输入 image.111111.xyz/图片链接

即可直接返回压缩为avif格式的图片

可以将此链接直接放入文章中 : ![image](https://image.111111.xyz/图片链接)

4. 原贴

https://www.nodeseek.com/post-182262-1