使用nodejs實現本地壓縮jpg,png圖片。
使用到的包
1.images 用於壓縮jpg
npm install images
yarn add images
2.imagemin 用於壓縮png
npm install imagemin yarn add imagemin //這里還需要一個imagemin的依賴包 npm install imagemin-pngquant yarn add imagemin-pngquant
舉例代碼:
const imagemin = require("imagemin")
const imageminPngquant = require('imagemin-pngquant');
const images = require("images")
let jpg = "d:/images/1.jpg" //目標圖片地址
let newjpg = "d:/new/1.jpg" //輸出圖片地址
//壓縮jpg 此API為同步方法,可以遍歷執行
images(jpg).save(newjpg, { quality: 60 }) //壓縮質量(0,100)
//壓縮png 此API為異步方法
let png = "d:/images/1.png" //目標圖片地址
let newpng = "d:/new/1.png" //輸出圖片地址
imagemin(png, {
destination: newpng,
plugins: [
imageminPngquant({
quality: [0.6, 0.7] //壓縮質量(0,1)
})
]
}).then(() => {
console.log("壓縮成功");
}).catch(err => {
console.log("壓縮失敗:"+err)
});
