web图像格式对比(四)
source link: https://icodex.me/webimage4/
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.
web图像格式对比(四)
nodejs 图像处理库
说完了有损压缩和无损压缩的图像格式,来整理下 nodejs 方面图像处理相关的库。
sharp
基于 libvips 实现,提供 JPEG、PNG、GIF、Webp、AVIF 以及 SVG 图像格式的处理,包括图像格式转换,图像尺寸缩放,图像组合,图像旋转,等等多种操作,也支持将图像转换成 base64 字符串。
例如将 png 转换成 avif
import sharp from 'sharp';
sharp('./images/rgb.png')
.toFormat('avif', { quality: 50 })
.toFile('build/images/rgb.avif')
.then(info => console.log(info));
例如将 jpeg 转成 base64
const resizedImageBuf = await require('sharp')(pathToMyImage)
.toBuffer();
console.log(`data:image/png;base64,${resizedImageBuf.toString('base64')}`);
imagemin(停止维护)
imagemin 是插件式的压缩图像的工具,可通过引入自定义的插件来支持不同图像格式的转换和图像尺寸的优化,文档相对简陋,并且本身已停止维护,常用的插件有以下这些:
import imagemin from 'imagemin';
import imageminWebp from 'imagemin-webp';
await imagemin(['images/*.{jpg,png}'], {
destination: 'build/images',
plugins: [
imageminWebp({ quality: 100 })
]
});
libsquoosh
Google 开发的 libSquoosh,支持使用 nodejs cli 转换图像格式的工具,支持 JPEG XL,具体的可以看这篇介绍 —— Introducing libSquoosh
其他构建工具
Webpack
版本 | loader | plugin |
---|---|---|
<= 4 | url-loader :支持读取图像并转换成 base64file-loader :支持读取图像 | imagemin-webpack-plugin(停止维护) image-minimizer-webpack-plugin:支持使用 imagemin 和libsquoosh 优化图像尺寸 |
5 | 内置支持 - assets module |
Vite
vite-plugin-imagemin:使用 imagemin 压缩图像
Rollup
@rollup/plugin-image:支持import
jpeg,png 等图像文件的语法并打包
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK