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 = `