Node.js图片处理库sharp的使用

 更新时间:2023年01月16日 14:16:58   作者:逆袭的菜鸟X  
这篇文章主要介绍了Node.js图片处理库sharp的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Node.js图片处理库sharp

1、sharp

sharp 是 Node.js 平台上相当热门的一个图像处理库,其实际上是基于 C 语言编写 的 libvips 库封装而来,因此高性能也成了 sharp 的一大卖点。

sharp 可以方便地实现常见的图片编辑操作,如裁剪、格式转换、旋转变换、滤镜添加等。

首先安装下sharp:

npm install sharp

2、源码

通过下面代码实现了自动转换输入图片到数组定义尺寸

const sharp = require("sharp");
const fs = require("fs");

/**
 * 1、toFile
 * @param {String} basePicture 源文件路径
 * @param {String} newFilePath 新文件路径
 */
function writeTofile(basePicture, newFilePath, width, height) {
  sharp(basePicture)
    .resize(width, height) //缩放
    .toFile(newFilePath);
}

function picTransition() {
  var picConfigure = [
    { name: "Default-568h@2x-1.png", width: 640, height: 1136 },
    { name: "Default-568h@2x.png", width: 640, height: 1136 },
    { name: "Default@2x-1.png", width: 640, height: 960 },
    { name: "Default@2x.png", width: 640, height: 960 },
    { name: "Loading@2x.png", width: 750, height: 1334 },
    { name: "Loading@3x.png", width: 1242, height: 2208 },
    { name: "LoadingX@3x.png", width: 1125, height: 2436 }
  ];
  picConfigure.map((item) => {
    writeTofile("./input.png", `./outImages/${item.name}`, item.width, item.height);
  });
}
picTransition();

resize参数

// 摘抄于sharp库
interface ResizeOptions {
    /** Alternative means of specifying width. If both are present this take priority. */
    width?: number;
    /** Alternative means of specifying height. If both are present this take priority. */
    height?: number;
    /** How the image should be resized to fit both provided dimensions, one of cover, contain, fill, inside or outside. (optional, default 'cover') */
    fit?: keyof FitEnum;
    /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */
    position?: number | string;
    /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */
    background?: Color;
    /** The kernel to use for image reduction. (optional, default 'lanczos3') */
    kernel?: keyof KernelEnum;
    /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */
    withoutEnlargement?: boolean;
    /** Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default true) */
    fastShrinkOnLoad?: boolean;
}

3、sharp的其他操作

// 跨平台、高性能、无运行时依赖

const sharp = require('sharp');
const fs = require('fs');
const textToSvg = require('text-to-svg');


const basePicture = `${__dirname}/static/云雾缭绕.png`;

// 流转Buffer缓存
function streamToBuffer(stream) {
  return new Promise((resolve, reject) => {
    const bufferList = []
    stream.on('data', data => {
      // 每一个data都是一个Buffer对象
      bufferList.push(data)
    })
    stream.on('error', err => {
      reject()
    })
    stream.on('end', () => {
      resolve(Buffer.concat(bufferList))
    })
  })
}

/**
 * 1、toFile
 * @param {String} basePicture 源文件路径
 * @param {String} newFilePath 新文件路径
 */
function writeTofile(basePicture, newFilePath) {
  sharp(basePicture)
    .rotate(20) // 旋转
    .resize(500, 500) //缩放
    .toFile(newFilePath)
}
// writeTofile(basePicture, `${__dirname}/static/云雾缭绕1.png`);

/**
 * 2、读取图片buffer
 * @param {String} basePicture 源文件路径
 */
function readFileBuffer(basePicture) {
  sharp(basePicture)
    .toBuffer()
    .then(data => {
      console.log(data)
    })
    .catch(err => {
      console.log(err)
    })
}
// readFileBuffer(basePicture);

/**
 * 3、对文件流进行处理
 * @param {String} basePicture 源文件路径
 */
function dealWithStream(basePicture) {
  // 读取文件流
  const readableStream = fs.createReadStream(basePicture)
  // 对流数据进行处理
  const transformer = sharp().resize({
    width: 200,
    height: 200,
    fit: sharp.fit.cover,
    position: sharp.strategy.entropy
  })
  // 将文件读取到的流数据写入transformer进行处理
  readableStream.pipe(transformer)

  // 将可写流转换为buffer写入本地文件
  streamToBuffer(transformer).then(function(newPicBuffer) {
    fs.writeFile(`${__dirname}/static/云雾缭绕2.png`, newPicBuffer, function(
      err
    ) {
      if (err) {
        console.log(err)
      }
      console.log('done')
    })
  })
}
// dealWithStream(basePicture);

/**
 * 4、将文件的转为JPEG,并对JPEG文件进行处理
 * @param {String} basePicture 源文件路径
 */
function dealWithBuffer(basePicture) {
  sharp(basePicture)
    .resize(300, 300, {
      fit: sharp.fit.inside,
      withoutEnlargement: true
    })
    .toFormat('jpeg')
    .toBuffer()
    .then(function(outputBuffer) {
      fs.writeFile(`${__dirname}/static/云雾缭绕3.jpeg`, outputBuffer, function(
        err
      ) {
        if (err) {
          console.log(err)
        }
        console.log('done')
      })
    })
}
// dealWithBuffer(basePicture)

/**
 * 5、添加水印
 * @param  {String} basePicture 原图路径
 * @param  {String} watermarkPicture 水印图片路径
 * @param  {String} newFilePath 输出图片路径
 */
function addWatermark(basePicture, watermarkPicture, newFilePath) {
  sharp(basePicture)
    .rotate(180) // 旋转180度
    .composite([
      {
        input: watermarkPicture,
        top: 10,
        left: 10
      }
    ]) // 在左上坐标(10, 10)位置添加水印图片
    .withMetadata() // 在输出图像中包含来自输入图像的所有元数据(EXIF、XMP、IPTC)。
    .webp({
      quality: 90
    }) //使用这些WebP选项来输出图像。
    .toFile(newFilePath)
    .catch(err => {
      console.log(err)
    })
  // 注意水印图片尺寸不能大于原图
}

// addWatermark(
//   basePicture,
//   `${__dirname}/static/水印.png`,
//   `${__dirname}/static/云雾缭绕4.png`
// )


 /**
  * 添加文字,类似添加水印
  * @param {String} basePicture 原图路径
  * @param {Object} font 字体设置
  * @param {String} newFilePath 输出图片路径
  * @param {String} text 待粘贴文字
  * @param {Number} font.fontSize 文字大小
  * @param {String} font.color 文字颜色
  * @param {Number} font.left 文字距图片左边缘距离
  * @param {Number} font.top 文字距图片上边缘距离
  */
function addText(basePicture, font, newFilePath) {
  const { fontSize, text, color, left, top } = font;
  // 同步加载文字转SVG的库
  const textToSvgSync = textToSvg.loadSync();
  // 设置文字属性
  const attributes = {
    fill: color
  };
  const options = {
    fontSize,
    anchor: 'top',
    attributes
  };
  // 文字转svg,svg转buffer
  const svgTextBuffer = Buffer.from(textToSvgSync.getSVG(text, options));

  // 添加文字
  sharp(basePicture)
    //  .rotate(180) // 旋转180度
    .composite([
      {
        input: svgTextBuffer,
        top,
        left
      }
    ]) // 在左上坐标(10, 10)位置添加文字
    .withMetadata() // 在输出图像中包含来自输入图像的所有元数据(EXIF、XMP、IPTC)。
    .webp({
      quality: 90
    }) //使用这些WebP选项来输出图像。
    .toFile(newFilePath)
    .catch(err => {
      console.log(err)
    });
}

addText(
  basePicture,
  {
    fontSize: 50,
    text: '洋溢洋溢洋溢',
    color: 'yellow',
    left: 100,
    top: 100
  },
  `${__dirname}/static/云雾缭绕5.png`
);

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 浅谈node中的cluster集群

    浅谈node中的cluster集群

    这篇文章主要介绍了浅谈node中的cluster集群,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • Node.js文件操作详解

    Node.js文件操作详解

    这篇文章主要介绍了Node.js文件操作详解,本文讲解了处理文件路径讲的一些方法、fs模块详细的使用和介绍等内容,需要的朋友可以参考下
    2014-08-08
  • 详解Wondows下Node.js使用MongoDB的环境配置

    详解Wondows下Node.js使用MongoDB的环境配置

    这篇文章主要介绍了详解Wondows下Node.js使用MongoDB的环境配置,这里使用到了Mongoose驱动来让JavaScript操作MongoDB,需要的朋友可以参考下
    2016-03-03
  • node通过npm写一个cli命令行工具

    node通过npm写一个cli命令行工具

    本篇文章主要介绍了node通过npm写一个cli命令行工具 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • 剖析Node.js异步编程中的回调与代码设计模式

    剖析Node.js异步编程中的回调与代码设计模式

    这篇文章主要介绍了Node.js异步编程中的回调与代码设计模式,虽然大多数场合回调编写时的长串括号不怎么好看,但Node的异步性能确实很好,需要的朋友可以参考下
    2016-02-02
  • Node.js操作MySQL8.0数据库无法连接的问题解决

    Node.js操作MySQL8.0数据库无法连接的问题解决

    使用node.js连接数据库MySQL 8时候,显示报错 ER_NOT_SUPPORTED_AUTH_MODE,本文就来介绍一下解决方法,感兴趣的可以了解一下
    2023-10-10
  • npm ci命令的基本使用方法

    npm ci命令的基本使用方法

    这篇文章主要给大家介绍了关于npm ci命令的基本使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • node.js中的events.emitter.removeAllListeners方法使用说明

    node.js中的events.emitter.removeAllListeners方法使用说明

    这篇文章主要介绍了node.js中的events.emitter.removeAllListeners方法使用说明,本文介绍了events.emitter.removeAllListeners 的方法说明、语法、接收参数、使用实例和实现源码,需要的朋友可以参考下
    2014-12-12
  • Node.js中防止错误导致的进程阻塞的方法

    Node.js中防止错误导致的进程阻塞的方法

    这篇文章主要介绍了Node.js中防止错误导致的进程阻塞的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-08-08
  • Node.js用Socket.IO做聊天软件的实现示例

    Node.js用Socket.IO做聊天软件的实现示例

    本文主要介绍了Node.js用Socket.IO做聊天软件的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-05-05

最新评论