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 = `
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值