通常我使用以下命令将png图像导入到画布中
const image = Canvas.LoadImage('url.png')
const canvas = Canvas.createCanvas(256,256)
const ctx = canvas.getContext('2d')
ctx.drawImage(image,256,256)但是当我尝试导入webp图像时,我得到一个错误,说webp不受支持。在对node-canvas问题的研究中,我发现this issue的导入问题似乎已经解决了,但我不知道现在如何导入webp图像。
我尝试从fix in the issue中使用Image、ImageFromBuffer(await fetch(url).buffer()),但两者都给出了错误。
发布于 2021-08-20 18:39:40
我使用Sharp库解决了这个问题。
首先获取文件作为缓冲区
// axios for remote images- maybe fs for local images?
const imageResponse = await axios.get(url, {
responseType: 'arraybuffer',
});使用sharp将文件转换为png:
const img = await sharp(imageResponse.data).toFormat('png').toBuffer();然后,您可以使用loadImage
const file = await loadImage(img).then((image) => {
ctx.drawImage(
image,
256,
256
);
return { buffer: canvas.toBuffer(), mimetype: `image/png` };
});https://stackoverflow.com/questions/65076410
复制相似问题