【问题标题】:Can we get height and width of image using sharp?我们可以使用sharp获得图像的高度和宽度吗?
【发布时间】:2020-10-20 12:05:49
【问题描述】:

我正在使用锐化来调整大部分图像的大小。所以我通过保留它们的纵横比将它们调整为 500px。此外,我想将高度调整为 500 像素,如果高度大于 with,则自动调整宽度,反之亦然。为此,我需要从图像缓冲区获取图像高度。我知道有相当数量的软件包可以这样做。但我希望如果我可以使用尖锐缓冲区本身来做到这一点。

【问题讨论】:

标签: node.js sharp


【解决方案1】:

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);

【讨论】:

  • 有没有办法在任何中间步骤之后获取图像的宽度和高度?假设我做了一个sharp(img).resize({width: 200}),现在我想知道图像的最终高度是多少(在将其写入文件之前)。
  • 应该可以在图片上使用元数据功能:sharp.pixelplumbing.com/api-input#metadata。这将为您提供图像尺寸等等!
【解决方案2】:

是的,您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 2023-04-04
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2015-08-16
    • 2012-01-03
    相关资源
    最近更新 更多