How to convert a remote webp image to a png image to load it into node-canvas
Asked Answered
B

1

8

Usually I import png images into Canvas by using

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

but when i try to import a webp image, I get an error saying that webp isn't supported. On research into the Issues of node-canvas I found this issue, The importing issue appears to be solved but I dont understand how to import the webp images now.

I tried using the Image, ImageFromBuffer(await fetch(url).buffer()) from the fix in the issue but both give errors.

Birchard answered 30/11, 2020 at 15:29 Comment(0)
Z
7

I solved it by using the library Sharp.

First get the file as a buffer

// axios for remote images- maybe fs for local images?
const imageResponse = await axios.get(url, {
        responseType: 'arraybuffer',
      });

Convert the file to png using sharp:

const img = await sharp(imageResponse.data).toFormat('png').toBuffer();

Then you can use loadImage

const file = await loadImage(img).then((image) => {
      ctx.drawImage(
        image,
        256,
        256
      );

      return { buffer: canvas.toBuffer(), mimetype: `image/png` };
    });
Zosema answered 20/8, 2021 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.