当前位置: 首页 > 后端技术 > Node.js

Nodejs实现批量裁剪图片功能

时间:2023-04-03 11:20:24 Node.js

1.初始化首先创建一个tailor-img文件夹,然后执行npminit-y初始化一个package.json2,安装相关插件archiver压缩文件canvas裁剪图片glob批量获取路径npmiarchivercanvasglob--save3、app。jsconstfs=require('fs')const{basename}=require('path')//压缩文件constarchiver=require('archiver')//画布库,用于裁剪图片const{createCanvas,loadImage}=require('canvas')//批量获取路径constglob=require('glob')constconfig=require('./config')//根据宽高获取配置functiongetOptions(options,config){const[sourceWidth,sourceHeight]=选项const{width,height,isWidth,isHeight,scale}=configconsthaveWidth=[width,(sourceHeight*width*scale)/sourceWidth]consthaveHeight=[(sourceWidth*height*scale)/sourceHeight,height]if(width===0||height===0){return[0,0]}if(width&&height){if(isWidth){returnhaveWidth}if(isHeight){returnhaveHeight}返回[width/scale,height/scale]}if(width&&!height){重新转haveWidth}if(height&&!width){returnhaveHeight}returnoptions.map((item)=>item/scale)}!(async()=>{constpaths=glob.sync('./images/*')//压缩成zipconstarchive=archiver('zip',{zlib:{level:9,},})//输出到当前文件夹的image-resize.zipconstoutput=fs.createWriteStream(__dirname+'/image-resize.zip')archive.pipe(output)for(leti=0;iitem/2)constoptions=getOptions(obj,config)constcanvas=createCanvas(...options)constctx=canvas.getContext('2d')ctx.drawImage(image,0,0,...options)archive.append(canvas.toBuffer(),{name:`${basename(path)}`})}})()4.config.js用于修改宽高的配置module.exports={width:300,height:'',//根据宽度比例缩放,优先级为Width:true,//根据高度比例缩放isHeight:false,//宽高整体缩放scale:1,}

最新推荐
猜你喜欢