当上传图像到时,我想调整大小,并将图像格式转换为webp。所以我用云函数创建了一个触发器。为此,我使用Node.js夏普库。
云函数正确调整图像大小,,但它始终保持原始格式.
这是转换和调整大小的代码:
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项目时,它可以正常工作。
更新
我正在使用Sharp0.26.1,我也按建议尝试了以前的版本,但是没有什么改变。
我也尝试过这样做,使用fs-额外的库来编写文件,但是结果仍然是一样的:调整大小和压缩工作是正确的,而格式转换没有。
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项目。不可能在本地测试这个云函数,因为没有官方的云存储本地模拟器)
发布于 2021-01-22 15:48:38
我和这件事斗争了好几个小时,这就是我终于成功的原因。确保您所设置的上载头的mimetype是“image/webp”,因为您使用它来上传到AWS/Azure/Digital。
发布于 2020-10-14 13:02:54
不要只使用toFormat()
,尝试使用它,然后是webp()
调用,如下所示:
return sharp(originalFile)
.rotate()
.resize(parseInt(width, 10), parseInt(height, 10), {
fit: "inside",
withoutEnlargement: true,
})
.toFormat("webp")
.webp({
quality: 80,
force: true
});
.toFile(resizedFile);
这应该能让它发挥作用。
https://stackoverflow.com/questions/64332954
复制相似问题