【问题标题】:How to convert a remote webp image to a png image to load it into node-canvas如何将远程 webp 图像转换为 png 图像以将其加载到节点画布中
【发布时间】:2021-03-12 13:01:39
【问题描述】:

通常我通过使用将 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。在研究 node-canvas 的问题时,我发现this issue,导入问题似乎已解决,但我现在不明白如何导入 webp 图像。

我尝试使用 fix in the issue 中的 Image、ImageFromBuffer(await fetch(url).buffer()),但都给出了错误。

【问题讨论】:

    标签: node.js canvas webp node-canvas


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-03
      • 2013-12-11
      • 2019-07-20
      • 1970-01-01
      • 2012-10-24
      • 2018-05-10
      • 2022-07-07
      • 2017-09-08
      相关资源
      最近更新 更多