我们可以使用Sharp获取图像的高度和宽度吗?

21

我正在使用Sharp来批量调整图像大小。因此,我将它们按比例保持缩放到500px。同时,我想将高度调整为500px,并在高度大于宽度或宽度大于高度时自动调整宽度。为了做到这一点,我需要从图像缓冲区获取图像和高度。我知道有很多可用的软件包可以实现这一点。但我希望能够使用Sharp缓冲区本身来完成。


1
阅读文档:https://sharp.pixelplumbing.com/api-input 以获取尺寸。或者直接使用 resize:https://sharp.pixelplumbing.com/api-resize#resize,它已经可以实现你想要的功能。 - x4rf41
3个回答

35

你可以使用Sharp的metadata()函数来获取图像的宽度和高度:

const image = await sharp(file.buffer)
const metadata = await image.metadata()
console.log(metadata.width, metadata.height)

您可以从metadata获取更多信息,这里是文档:https://sharp.pixelplumbing.com/api-input#metadata


2
你不需要使用await等待_Sharp_构造函数的执行。 - Константин Ван
2
我绝不是JavaScript专家,但文档说,我们可以https://sharp.pixelplumbing.com/api-input#examples - devAgam
2
如果您参考以下示例 const metadata = await sharp(input).metadata();,实际上我们在这里使用了 await 函数 metadata(),它也可以分为两步完成,如下所示:const image = sharp(input); const metadata = await image.metadata(); - Stephane L
1
你可以将它缩短很多。const { width, height } = await sharp(file.buffer).metadata(); - user2831723

11

要获取输入图像头文件中记录的维度:

const image = await sharp(file.buffer);
const metadata = await image.metadata();
console.log(metadata.width, metadata.height);

然而,像image.resize(...)这样的操作不会影响.metadata()。要在对图像执行操作后获取其尺寸,请使用.toBuffer({resolveWithObject:true})

const image = await sharp(file.buffer);
const resizedImage = image.resize(640);
const { info } = await resizedImage.png().toBuffer({ resolveWithObject: true });
console.log(info.width, info.height);

2

Sharp非常灵活,它有许多调整图像大小的选项。使用fit: "contain"选项应该可以实现您的愿望。

当然还有其他选项,在这里有文档记录:https://sharp.pixelplumbing.com/api-resize#resize

您还可以指定填充调整后图像内部空间的背景颜色,我在这里使用的是白色。

代码大致如下:

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

const inputDir = "./input-images";
const outputDir = "./output-images";
const requiredDimension = 500;

const inputImages = fs.readdirSync(inputDir).map(file => path.join(inputDir, file));

function resizeImage(imagePath) {

    sharp(imagePath)
    .resize( { width: requiredDimension, height: requiredDimension,  fit: "contain", background: { r: 255, g: 255, b: 255, alpha: 1 }})
    .toFile(path.join(outputDir, path.basename(imagePath) + "-resized" + path.extname(imagePath)), (err, info) => { 
        if (err) {
            console.error("An error occurred resizing image:", err);
        }
    });
}

// Ensure output dir exists...
if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir)
}
inputImages.forEach(resizeImage);

2
有没有办法在任何中间步骤后获取图像的宽度和高度?比如我执行了 sharp(img).resize({width: 200}),现在我想知道图像的结果高度是多少(在将其写入文件之前)。 - Arash Motamedi
7
您应该能够在图像上使用元数据功能:https://sharp.pixelplumbing.com/api-input#metadata。这将为您提供图像尺寸和更多信息! - Terry Lennox
1
元数据函数在序列开始时提供图像尺寸,而不是在中间步骤之后。 - allanberry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接