使用Node搭建超高压缩比的图片(webp)压缩服务
图片压缩技术选型优先考虑webp技术。
# 安装依赖包
npm i imagemin imagemin-webp --save
1
# webp压缩
const imagemin = require("imagemin");
const imageminWebp = require("imagemin-webp");
const compImg = async function (file) {
let compfile = await imagemin([`public/images/${file}`], {
destination: "public/compressed-images",
plugins: [imageminWebp({ quality: 75 })],// 压缩质量75%
});
return compfile;
};
module.exports = compImg;
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 编写图片上传接口
var express = require("express");
var router = express.Router();
var multer = require("multer");
const path = require("path");
const compImg = require("../src/comp"); // 引入comp.js的压缩函数
let filename = "";
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "public/images");
},
filename: function (req, file, cb) {
let exname = path.extname(file.originalname);
filename = file.fieldname + "-" + Date.now() + exname;
cb(null, filename);
},
});
var upload = multer({ storage: storage });
router.post("/webp/compImg", upload.single("file"), async (req, res, next) => {
let compfile = await compImg(filename);
res.send({
code: 200,
data: compfile ,
msg: "ok",
});
});
module.exports = router;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 兼容程度
webp格式的图片在主流浏览器中的兼容程度: 在Safari浏览器支持程度不高,且小程序中不支持。为了解决这一问题,可以在webp压缩后返回了该文件的buffer数据流,即使是webp方式压缩后的base64数据也可以使用其他格式解析,并不冲突。
router.post("/webp/compImg", upload.single("file"), async (req, res, next) => {
let compfile = await compImg(filename);
let data = [];
compfile.map(el => {
let buffer = Buffer.from(el.data, "utf-8");
let base64Str = buffer.toString("base64");
console.log(compfile);
return data.push(base64Str);
});
res.send({
code: 200,
data,
msg: "ok",
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
规避了格式兼容问题,提高了加载速度,节省了存储资源及网络带宽资源,完美!
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13