1、初始化
首先新建一個 tailor-img 文件夾燎孟,接著執(zhí)行 npm init -y 初始化一個package.json
2、安裝相關(guān)插件
- archiver 壓縮文件
- canvas 裁剪圖片
- glob 批量獲取路徑
npm i archiver canvas glob --save
3涤姊、app.js
const fs = require('fs')
const { basename } = require('path')
// 壓縮文件
const archiver = require('archiver')
// canvas庫疹瘦,用于裁剪圖片
const { createCanvas, loadImage } = require('canvas')
// 批量獲取路徑
const glob = require('glob')
const config = require('./config')
// 根據(jù)寬高獲取配置
function getOptions(options, config) {
const [sourceWidth, sourceHeight] = options
const { width, height, isWidth, isHeight, scale } = config
const haveWidth = [width, (sourceHeight * width * scale) / sourceWidth]
const haveHeight = [(sourceWidth * height * scale) / sourceHeight, height]
if (width === 0 || height === 0) {
return [0, 0]
}
if (width && height) {
if (isWidth) {
return haveWidth
}
if (isHeight) {
return haveHeight
}
return [width / scale, height / scale]
}
if (width && !height) {
return haveWidth
}
if (height && !width) {
return haveHeight
}
return options.map((item) => item / scale)
}
!(async () => {
const paths = glob.sync('./images/*')
// 壓縮成zip
const archive = archiver('zip', {
zlib: {
level: 9,
},
})
// 輸出到當(dāng)前文件夾下的 image-resize.zip
const output = fs.createWriteStream(__dirname + '/image-resize.zip')
archive.pipe(output)
for (let i = 0; i < paths.length; i++) {
const path = paths[i]
const image = await loadImage(path)
const { width, height } = image
// 由于使用了擴展運算符展開對象生蚁,這里需要為對象定義迭代器
const obj = { width, height }
obj[Symbol.iterator] = function () {
return {
next: function () {
let objArr = Reflect.ownKeys(obj)
if (this.index < objArr.length - 1) {
let key = objArr[this.index]
this.index++
return { value: obj[key] }
} else {
return { done: true }
}
},
index: 0,
}
}
// 默認縮放2倍
// const options = [width, height].map((item) => item / 2)
const options = getOptions(obj, config)
const canvas = createCanvas(...options)
const ctx = canvas.getContext('2d')
ctx.drawImage(image, 0, 0, ...options)
archive.append(canvas.toBuffer(), { name: `${basename(path)}` })
}
})()
4噩翠、config.js用于修改寬高等配置
module.exports = {
width: 300,
height: '',
// 根據(jù)寬度等比縮放,優(yōu)先級更高
isWidth: true,
// 根據(jù)高度等比縮放
isHeight: false,
// 寬高整體縮放
scale: 1,
}