您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 滁州分类信息网,免费分类信息发布

nodejs怎么实现对图片进行批量裁剪?

2025/3/9 4:36:00发布4次查看
nodejs怎么实现对图片进行批量裁剪?下面本篇文章给大家介绍一下nodejs实现批量裁剪图片功能的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
相关推荐:《nodejs 教程》
1、初始化首先新建一个 tailor-img 文件夹,接着执行 npm init -y 初始化一个package.json
2、安装相关插件archiver  压缩文件canvas  裁剪图片glob  批量获取路径npm i archiver canvas glob --save
3、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 // 由于使用了扩展运算符展开对象,这里需要为对象定义迭代器 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: '', // 根据宽度等比缩放,优先级更高 iswidth: true, // 根据高度等比缩放 isheight: false, // 宽高整体缩放 scale: 1,}
更多编程相关知识,请访问:编程视频课程!!
以上就是nodejs怎么实现对图片进行批量裁剪?的详细内容。
滁州分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录