我正在尝试从base64编码的字符串调整图像的大小。我可以在nodejs
中使用c来完成此操作。Sharp
使用Promises,所以我知道我必须使用异步方法。调整大小后,我需要将其转换回base64字符串。我通常使用nodejs Buffer
将图像转换为缓冲区,然后使用'toString()
方法将其转换回base64。
这就是我的代码:
async function resizer(base64, width = 224, height = 224) {
if (!base64) {
throw console.error("not a base64 string")
} else {
const Buffer = require("buffer").Buffer
let base64buffer = Buffer.from(base64, "base64")
const image = await sharp(base64buffer)
.resize({
width: width,
height: height,
fit: sharp.fit.cover,
})
.rotate(90)
.toBuffer()
const newBase64 = image.toString("base64")
return newBase64
}
}
const resizedBase64 = resizer(base64Image).then((result) => {
console.log(result)
return result
})
console.log(resizedBase64)
函数采用base64字符串作为参数。然后它被转换成一个缓冲区,我让sharp做它的事情。然后返回新生成的字符串。然而,当我将其存储为变量时,它会返回一个Promise {pending}
。当我只是在.then()
回调中console.log时,它确实记录了新的base64字符串。
有人知道怎么解决这个问题吗?稍后我需要在代码中使用新的base64。
提前谢谢!
您只需添加一个await
即可从promise中获得解析值:
const resizedBase64 = await resizer(base64Image);
编辑:这里需要理解的是,resizer
函数包含一些异步代码(来自Sharp库(,这些代码返回promise。因此,即使在函数中使用await
,函数也将始终返回值的promise,而不是值本身。函数的调用方将收到promise,并且必须等待它才能获得实际值。
在调用函数resizer
时,如果您不在异步上下文中并且不能使用await
,则有几种解决方案可用。解决方案1:使用IIFE
(async() => {
const resizedBase64 = await resizer(base64Image);
console.log(resizedBase64);
// the rest of your code goes here
})();
解决方案2:声明一个异步函数(与以前基本相同(
async main() => {
const resizedBase64 = await resizer(base64Image);
console.log(resizedBase64);
// the rest of your code goes here
});
main();
解决方案3:将代码放在then
回调中
resizer(base64Image).then((resizedBase64) => {
console.log(resizedBase64);
// the rest of your code goes here
});