1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > nodejs怎么实现对图片进行批量裁剪?

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

时间:2024-01-06 06:47:34

相关推荐

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

web前端|js教程

node.js,javascript,裁剪图片

web前端-js教程

nodejs怎么实现对图片进行批量裁剪?下面本篇文章给大家介绍一下nodejs实现批量裁剪图片功能的方法

手机网页游戏源码,旧电脑安装ubuntu,tomcat8 内存泄漏,楼盘字典 爬虫,php花店系统源码,做百度seo优化去哪里找客户lzw

源码购买 文件,ubuntu要关闭rst,如何防止爬虫程序,php shull,西安seo洛阳lzw

《nodejs 教学》

android 好看源码,ubuntu eno1,豆瓣音乐爬虫软件,分组php,度宝seolzw

1、初始化

首先新建一个 tailor-img 文件夹,接着执行 npm init -y 初始化一个package.json

2、安装相关插件

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)// 根据宽高获取配置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 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,}

编程视频课程!!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。