NodeJS 我们可以得到的高度和宽度的图像使用夏普?

cqoc49vn  于 2023-05-28  发布在  Node.js
关注(0)|答案(3)|浏览(250)

我使用夏普调整图像的体积。所以我通过保留它们的宽高比将它们的大小调整为500px。此外,我想调整高度为500px和自动调整宽度,如果高度大于宽度,反之亦然。要做到这一点,我需要得到图像,高度从图像缓冲区。我知道有相当数量的软件包可以这样做。但我希望如果我能做到这一点使用夏普缓冲本身。

voase2hg

voase2hg1#

是的,你可以通过使用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

hsgswve4

hsgswve42#

要获取输入图像标题中记录的尺寸:

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

lqfhib0f3#

夏普是非常灵活的,它有许多选项来调整图像的大小。使用拟合选项:“包容”应该实现你的愿望。
当然,还有其他的,记录在这里: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);

相关问题