【发布时间】:2021-01-27 15:47:53
【问题描述】:
将图片上传到 Firebase Cloud Storage 时,我想调整图片大小并将图片格式转换为 webp。所以我用 Cloud Function 创建了一个触发器。为此,我使用了 Node.js Sharp 库。
Cloud Function 可以正确调整图像大小,但它始终让我保持原始格式。
这是转换和调整大小的代码:
function resize(originalFile, resizedFile, size) {
let height, width;
if (size.indexOf(",") !== -1) {
[width, height] = size.split(",");
} else if (size.indexOf("x") !== -1) {
[width, height] = size.split("x");
} else {
throw new Error("height and width are not delimited by a ',' or a 'x'");
}
return sharp(originalFile)
.rotate()
.toFormat("webp", {
quality: 80,
force: true
})
.resize(parseInt(width, 10), parseInt(height, 10), {
fit: "inside",
withoutEnlargement: true,
}).toFile(resizedFile);
}
在本地的node.js项目上运行,效果很好。
更新
我使用的是 Sharp 0.26.1,我也按照建议尝试了以前的版本,但没有任何改变。
我也试过了,用fs-extra库写文件,结果还是一样:resize和compression正常,而格式转换不行。
async function resize(originalFile, resizedFile, size) {
let height, width;
if (size.indexOf(",") !== -1) {
[width, height] = size.split(",");
}
else if (size.indexOf("x") !== -1) {
[width, height] = size.split("x");
}
else {
throw new Error("height and width are not delimited by a ',' or a 'x'");
}
const data = await sharp(originalFile)
.rotate()
.toFormat("webp")
.resize(parseInt(width, 10), parseInt(height, 10), {
fit: "inside",
withoutEnlargement: true,
})
.webp({
quality: 80,
force: true
})
//.toFile(resizedFile);
.toBuffer();
fs.writeFileSync(resizedFile, data);
}
再次,在本地启动代码,它工作正常。 (当我说“本地”时,我的意思是在 node.js 项目上。无法在本地测试此 Cloud Function,因为没有官方的 Cloud Storage 本地模拟器)
【问题讨论】:
标签: javascript node.js firebase google-cloud-functions sharp