我正在使用Sharp来批量调整图像大小。因此,我将它们按比例保持缩放到500px。同时,我想将高度调整为500px,并在高度大于宽度或宽度大于高度时自动调整宽度。为了做到这一点,我需要从图像缓冲区获取图像和高度。我知道有很多可用的软件包可以实现这一点。但我希望能够使用Sharp缓冲区本身来完成。
我正在使用Sharp来批量调整图像大小。因此,我将它们按比例保持缩放到500px。同时,我想将高度调整为500px,并在高度大于宽度或宽度大于高度时自动调整宽度。为了做到这一点,我需要从图像缓冲区获取图像和高度。我知道有很多可用的软件包可以实现这一点。但我希望能够使用Sharp缓冲区本身来完成。
你可以使用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
await
等待_Sharp_构造函数的执行。 - Константин Ванconst metadata = await sharp(input).metadata();
,实际上我们在这里使用了 await
函数 metadata()
,它也可以分为两步完成,如下所示:const image = sharp(input); const metadata = await image.metadata();
- Stephane Lconst { width, height } = await sharp(file.buffer).metadata();
- user2831723要获取输入图像头文件中记录的维度:
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);
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})
,现在我想知道图像的结果高度是多少(在将其写入文件之前)。 - Arash Motamedi