网站被黑了,什么网站做新闻更好,保险设计素材网站,wordpress标签导航Sharp是一个基于libvips的高性能Node.js图像处理库#xff0c;它提供了广泛的功能#xff0c;包括调整大小、裁剪、旋转、格式转换等。Sharp可以处理多种图像格式#xff0c;并且能够高效地转换图像格式。 相关说明及用法看#xff1a;https://sharp.nodejs.cn/ 安装#…Sharp是一个基于libvips的高性能Node.js图像处理库它提供了广泛的功能包括调整大小、裁剪、旋转、格式转换等。Sharp可以处理多种图像格式并且能够高效地转换图像格式。 相关说明及用法看https://sharp.nodejs.cn/ 安装Sharpnpm install sharp 以及安装npm install --save text-to-svg text-to-svg将文本转换为SVG路径而无需本地依赖,相关用法及说明看https://www.npmjs.com/package/text-to-svg 上代码
const sharprequire(sharp);
const fsrequire(fs);
const textToSvgrequire(text-to-svg);const basePicture${__dirname}/img/123.jpg;//转化Buffer流对象并将buffer流合并成一个并期约返回
function streamToBuffer(stream)
{return new Promise((resolve,reject){const bufferList[];//图片流数据stream.on(data,data{bufferList.push(data);})stream.on(error,err{reject();})//end为追加数据stream.on(end,(){//这里是合并buffer对象resolve(Buffer.concat(bufferList));})})
}//生成新图片并追加新图片的格式大小覆盖区域等
function dealWithStream(basePicture)
{const readableStreamfs.createReadStream(basePicture);const transformersharp().resize({width:100,height:100,fit:sharp.fit.cover,position:sharp.strategy.entropy})//console.log(transformer);//将transformer流数据追加进行处理readableStream.pipe(transformer);streamToBuffer(transformer).then(function(newPicBuffer){//写入新图片中fs.writeFile(${__dirname}/img/water.png,newPicBuffer,function(err){if(err){console.log(err);return;}console.log(done);})})}//dealWithStream(basePicture);
//将图片转为jpeg,并对jpeg文件进行处理
function dealWithBuffer(basePicture)
{sharp(basePicture).resize(800,600,{fit:sharp.fit.inside,withoutEnlargement:true}).toFormat(webp).toBuffer().then(function(outputBuffer){fs.writeFile(${__dirname}/img/3.webp,outputBuffer,function(err){if(err){console.log(err);return;}console.log(done);})})
}//dealWithBuffer(basePicture);
//添加文字水印
function addText(basePicture,font,newFilePath)
{const {fontSize,text,color,left,top}font;const textToSvgSynctextToSvg.loadSync();const attributes{fill:color};const options{fontSize,anchor:top,attributes};const svgTextBufferBuffer.from(textToSvgSync.getSVG(text,options));//添加文字sharp(basePicture).composite([{input:svgTextBuffer,top,left}]).withMetadata() // 在输出图像中包含来自输入图像的所有元数据(EXIF、XMP、IPTC)。.toFormat(webp) //生成新的图片格式为webp.toFile(newFilePath) .then(info{if(!!info){console.log(水印已经生成);}}).catch(err{console.log(err);})
}/*
addText(basePicture,{fontSize:24,text:喜气洋洋,color:white,left:200,top:200
},${__dirname}/img/6.webp);
*///添加图片水印,水印图片一定要小于原图
function addWatermark(basePicture,watermarkPicture,newFilePath)
{sharp(basePicture)//.rotate(180) //旋转180度.composite([{input:watermarkPicture,blend:overlay,globalAlpha:0.5,left:50,top:50 }])//在左上坐标(10,10)位置添加水印图片,composite为合成图片.withMetadata().webp({quality:90}).toFile(newFilePath).then(result{if(result){console.log(水印已经添加);}}).catch(err{console.log(err);})sharp.cache(false);
}//dealWithStream(./img/300.jfif);
let waterPic${__dirname}/img/water.png
addWatermark(basePicture,waterPic,./img/7.webp);