nodejs怎么实现对图片进行批量裁剪?下面本篇文章给大家介绍一下nodejs实现批量裁剪图片功能的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
相关:《nodejs 教程》
1、初始化
首先新建一个 tailor-img 文件夹,接着执行 npm init -y 初始化一个package.json
2、安装相关插件archiver 压缩文件canvas 裁剪图片glob 批量获取路径npm i archiver canvas glob --save3、app.jsconst 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') // 根据宽高获取配置 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, }, }) // 输出到当前文件夹下的 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 // 由于使用了扩展运算符展开对象,这里需要为对象定义迭代器ex < 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: '', // 根据宽度等比缩放,优先级更高 isWidth: true, // 根据高度等比缩放 isHeight: false, // 宽高整体缩放 scale: 1, }
编程视频课程!!
韩国国税厅官员提议修订《刑事诉讼法》,以强化对个人自持虚拟资产的扣押执行规则。今年...
2 韩国股市与纳斯达克100指数相关系数升至消息,据彭博社披露,韩国综合股价指数与纳斯达克100指数的60日相关系数升至0.46,接近过去...
3 Polymarket:美联储7月29日维持利率不变概率消息,Polymarket交易者目前预计美联储在7月29日的决策中维持利率不变的概率为93.5%。...
4 长鑫存储巨鲸挂出832万美元卖单,挂单规消息,长鑫存储巨鲸在HyperLiquid上挂出832万美元的卖单,挂单规模已超过CXMT单日成交额。当前...
5 BTC ETF两周吸引2.73亿美元资金消息,BTC交易所交易基金在两周内吸引了2.73亿美元的资金流入,尽管这一数字与此前八周流出...
6 Schwab新兴市场ETF与iShares全球ETF:哪个更适消息,Schwab新兴市场ETF与iShares全球ETF之间的对比引发了投资者的关注。Schwab ETF主要针对新兴经...
7 沉睡鲸鱼在5年后转移700枚BTC,当前价值约一只沉睡的鲸鱼在5年后转移了700枚比特币,最初购买时花费约2234万美元,目前价值约4530万美...
8 Zhu Su:石油或许是AI的最佳类比,最终将消息,三箭资本联合创始人Zhu Su表示,石油或许是AI的最佳类比,两者都存在多种形态并最终走...
9 币安将于7月21日停止支持MOVR和GLMR主网充消息,币安官方公告称,将于2026年7月21日19:00停止支持moonriver 和moonbeam 主网的充值和提现业务...
10 摩根士丹利:欧洲柴油供应紧缩压力或将消息,摩根士丹利指出,由于一系列重大供应挑战同时出现,欧洲正面临柴油供应紧缩局面,...
成都来彰科技 蜀ICP备2025134723号-1
资讯来源互联网,如有版权问题请联系管理员删除。