首页 > 解决方案 > 如何将远程 webp 图像转换为 png 图像以将其加载到节点画布中

问题描述

通常我通过使用将 png 图像导入 Canvas

const image = Canvas.LoadImage('url.png')
const canvas = Canvas.createCanvas(256,256)
const ctx = canvas.getContext('2d')
ctx.drawImage(image,256,256)

但是当我尝试导入 webp 图像时,我收到一条错误消息,指出不支持 webp。在对节点画布问题的研究中,我发现了这个问题,导入问题似乎已解决,但我现在不明白如何导入 webp 图像。

我尝试使用问题修复中的 Image, ImageFromBuffer(await fetch(url).buffer()) ,但都给出错误。

标签: node.jscanvaswebpnode-canvas

解决方案


我通过使用库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` };
    });

推荐阅读