如何使用Sharp库在NodeJ中创建缩略图?

时间:2019-08-24 16:31:23

标签: node.js image npm

我正在尝试找到适合图像处理的库,
基本上,我有一个Resizing, Compressing and creating thumbnails图片的用例,
我发现sharp似乎是图像处理中流行的节点库选择,

我可以执行一些基本操作,例如调整图像大小,但是
我找不到一种方法来创建原始图像的缩略图或较小尺寸的图像。
有人可以指出使用sharp库创建缩略图和较小分辨率图像的正确代码吗?

示例工作代码- const sharp = require('sharp');

let test = async () => {

    await sharp('/pathToImage/test.jpg')
    .resize({
        fit: sharp.fit.outside
    })
    .sharpen()
    .toFile('fitOutside.jpg')
    .then(info => { 
        console.log(info);
    })
    .catch(err => {
        console.log(err);
    });

};

test();

参考-
http://sharp.pixelplumbing.com/en/stable/api-resize/
https://sharp.pixelplumbing.com/en/stable/api-resize/#examples_2

1 个答案:

答案 0 :(得分:3)

如果同时提供宽度和高度,则通常需要在一个轴上添加或删除像素。您可以使用fit参数来控制它的作用:

http://sharp.pixelplumbing.com/en/stable/api-resize/

默认值为centre,听起来像您更喜欢outside