Sharp是一个基于libvips的高性能Node.js图像处理库,它提供了广泛的功能,包括调整大小、裁剪、旋转、格式转换等。Sharp可以处理多种图像格式,并且能够高效地转换图像格式。
相关说明及用法看:https://sharp.nodejs.cn/
安装:Sharp:npm install sharp
以及安装:npm install --save text-to-svg
text-to-svg将文本转换为SVG路径,而无需本地依赖,相关用法及说明看https://www.npmjs.com/package/text-to-svg
上代码
const sharp=require('sharp');
const fs=require('fs');
const textToSvg=require('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 readableStream=fs.createReadStream(basePicture);const transformer=sharp().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 textToSvgSync=textToSvg.loadSync();const attributes={fill:color};const options={fontSize,anchor:'top',attributes};const svgTextBuffer=Buffer.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');