如何基于 mozjpeg 优化 JPEG 质量到 85%?
解读
在国内前端面试中,面试官抛出“Cypress 如何基于 mozjpeg 把 JPEG 压到 85% 质量”这类题,表面看是“图片压缩”,实质想考察三件事:
- 你是否理解 Cypress 任务插件机制(cy.task)——浏览器内无法直接调原生二进制,必须把 heavy-lifting 放到 Node 层;
- 你是否熟悉 mozjpeg 的 CLI 与 Node 封装(imagemin-mozjpeg / mozjpeg-cli)——国内镜像源、二进制安装、CI 缓存都是落地痛点;
- 你是否能把“压缩”集成到测试流水线,并给出 可重复、可断言、可回滚 的方案,而不是“跑一遍脚本就完”。
一句话:考的不是“怎么压”,而是“怎么在 Cypress 体系里稳健地压”。
知识点
-
Cypress 任务插件
- 浏览器沙箱限制 → 压缩必须放到 plugins/index.js 的
on('task'); - task 必须返回 Promise,且可序列化;
- 失败时返回
null或抛错,Cypress 会重试 3 次。
- 浏览器沙箱限制 → 压缩必须放到 plugins/index.js 的
-
mozjpeg 国内可用方案
- imagemin-mozjpeg:纯 Node 封装,依赖 mozjpeg 预编译二进制;
- mozjpeg-cli:直接调命令行,需确保
mozjpeg@^8.0在 PATH; - 镜像源:
.npmrc里加canvas_binary_host_mirror=https://npmmirror.com/mirrors/mozjpeg-bin/可解决下载 404。
-
质量参数
- mozjpeg 质量 0–100,85 是视觉无损与体积的平衡点;
- 渐进式(progressive)默认开启,可再降 5–8% 体积;
- 需保留 EXIF 时加
-copy all,否则默认 strip。
-
Cypress 断言策略
- 压缩后体积必须 < 原图 60%,用
cy.readFile('dist.jpg','binary').should('have.length.lt', origSize*0.6); - 像素差异 < 1% 用 pixelmatch 做回归,防止“压糊”;
- 把压缩耗时也写进自定义命令,防止 CI 超时(国内 GitLab Runner 2 vCPU 常压 4 K 图 > 3 s)。
- 压缩后体积必须 < 原图 60%,用
-
缓存与回滚
- 在
cypress.config.js里配env.mozjpegCacheDir=./cypress/cache/jpeg; - task 先算文件 md5 → 命中缓存直接返回,CI 秒级增量;
- 失败时把原图拷贝到
cypress/screenshots/backup,方便回滚。
- 在
答案
- 安装依赖(淘宝源加速)
npm i -D imagemin imagemin-mozjpeg cross-env
# 解决二进制下载慢
export npm_config_canvas_binary_host_mirror=https://npmmirror.com/mirrors/mozjpeg-bin/
npm rebuild imagemin-mozjpeg
- 在
cypress/plugins/index.js注册任务
const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const path = require('path');
const fs = require('fs');
module.exports = (on, config) => {
on('task', {
async mozjpeg85({ src, dest }) {
const buf = await imagemin([src], {
destination: path.dirname(dest),
plugins: [
imageminMozjpeg({ quality: 85, progressive: true })
]
});
// 返回新文件路径与体积,供测试断言
const out = dest;
fs.renameSync(buf[0].destinationPath, out);
return { path: out, size: fs.statSync(out).size };
}
});
};
- 自定义命令封装(
cypress/support/commands.js)
Cypress.Commands.add('optimizeJpeg', (src, dest) => {
return cy.task('mozjpeg85', { src, dest }).then((result) => {
cy.readFile(result.path, 'binary').should('have.length.lt', result.size * 1.1);
return result.path;
});
});
- 测试用例(
cypress/e2e/image-optimize.cy.js)
describe('JPEG 质量压缩到 85%', () => {
const raw = 'cypress/fixtures/demo.jpg';
const opt = 'cypress/downloads/demo-q85.jpg';
it('压缩后体积小于 60% 且像素差异 < 1%', () => {
cy.optimizeJpeg(raw, opt).then((filePath) => {
cy.readFile(raw, 'binary').then((orig) => {
cy.readFile(filePath, 'binary').should('have.length.lt', orig.length * 0.6);
});
// 像素级回归(可选)
cy.task('pixelDiff', { img1: raw, img2: filePath, threshold: 0.01 });
});
});
});
- CI 集成(
.gitlab-ci.yml片段)
variables:
npm_config_canvas_binary_host_mirror: "https://npmmirror.com/mirrors/mozjpeg-bin/"
test:
image: cypress/browsers:node-18.16.0-chrome-114
cache:
key: mozjpeg-bin
paths:
- ./cypress/cache/jpeg
script:
- npm ci
- npx cypress run --env mozjpegCacheDir=./cypress/cache/jpeg
至此,“基于 mozjpeg 把 JPEG 压到 85% 质量” 已完整嵌入 Cypress 测试生命周期,具备缓存、断言、回滚能力,可直接应对国内面试官的“落地拷问”。
拓展思考
-
如果图片在 CDN,是否先 cy.request 拉回再压?
拉回后放cypress/fixtures,再走上述 task,可避免跨域;大文件用cy.request({ encoding: 'binary' })防止 base64 膨胀。 -
多质量档位 A/B:
在cypress.config.js里配env.quality=75/85/95,用 Cypress 数据驱动 同一套 case 跑三档,输出体积-SSIM 曲线,让产品自己选“性价比”。 -
与视觉回归结合:
把压缩后的图作为“新基准”自动上传到 阿里云 OSS + 视觉对比服务(如 Percy 国内加速),MR 阶段若像素差异 > 0.5% 就阻断,防止“压糊”上线。 -
WebP 并行输出:
在 task 里同时跑imagemin-webp {quality:85},一份源码双格式,再写 Cypress 断言对比 WebP 体积比 JPEG 再降 30%,面试加分项。 -
二进制缓存下沉到 Docker 层:
把mozjpeg-c预编译进公司私有镜像cypress-mozjpeg:1.0.0,CI 无需 rebuild,平均节省 40 s,适合国内 GitLab Runner 资源紧张场景。