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

Node.js——切

时间:2023-04-03 19:54:14 Node.js

看到一篇juejin的文章,百万PV商城实战系列-前端图片资源优化,实战,影响,通过代码安装切图#buildafilenpminit#安装两个依赖npmiimage-sizesharp的代码constsizeOf=require('image-size');constsharp=require('sharp');constcurrentImageInfo=sizeOf('./wallhaven-3zwvk3.jpg')//加载一张图片FigureletclientHeight=currentImageInfo.heightconsole.log(currentImageInfo)constheights=[]constSPLIT_HEIGHT=200while(clientHeight>0){//当裁剪高度足够时if(clientHeight>=SPLIT_HEIGHT){heights.push(SPLIT_HEIGHT)clientHeight-=SPLIT_HEIGHT}else{//当切割高度不够时,直接切割成一块heights.push(clientHeight)clientHeight=0}}console.log(heights)lettop=0heights.forEach((h,index)=>{sharp('./wallhaven-3zwvk3.jpg').extract({left:0,top:top,width:currentImageInfo.width,height:h}).toFile(`./img/split_${index+1}_block.jpg`,(err,info)=>{if(!err){onsole.log(`split_${index+1}_block.jpg拆分成功`)}else{console.log(JSON.stringify(err),'error')}})top+=h})执行nodeindex.jsextensionsharp一个使用高速node.js将普通的大图转换成更小的,用于网络友好的JPEG、PNG、WebP等不同大小图像的优秀模块调整图像大小通常比使用最快的ImageMagick和GraphicsMagick设置快4到5倍从左边缘零开始提取图像左侧区域-indexedoffsetfromtopzero-indexedoffsetfromtopedgewidth提取图像的宽度height提取图像的高度toFile将输出图像数据写入文件。如果没有选择输出格式,则从扩展名推断,支持JPEG、PNG、WebP、TIFF、DZI和libvip的V格式。请注意,原始像素数据仅支持缓冲区输出。当没有提供回调时,返回一个PromisefileOut(String)以写入图像数据的路径。回调(函数)在完成时使用两个参数(错误、信息)调用。info包含输出图像格式、大小(字节)、宽度、高度、通道和预乘(表示是否使用预乘)。还包括使用裁剪策略时的cropOffsetLeft和cropOffsetTop示例。toFile(`./img/split_${index+1}_block.jpg`,(err,info)=>{if(!err){onsole.log(`split_${index+1}_block.jpg切割成功`)}else{console.log(JSON.stringify(err),'error')}}).toFile(`./img/split_${index+1}_block.jpg`).then(info=>{console.log(`split_${index+1}_block.jpg切割成功`)}).catch(err=>{console.log(JSON.stringify(err),'error')})sharp.js中文文档image-size.js文件为什么在Nodejs中不能require直接导入图片?constimg=require('./wallhaven-3zwvk3.jpg');用node执行这段代码,会报错,导致题目问的.js、.json、.node的扩展名。这个节点的加载模块机制是相关的。我经常写Vue,因为Vue使用了webpack,所以在Vue中是可以使用的,webpack会识别require或者导入并转换成自己的webpack模块,比如convertrequireto__webpack_require__。但是webpack只能识别JS,所以webpack有一个重要的概念Loader,可以通过file-loader或者url-loader来识别非js的图片文件。浅谈Node.js模块机制