Search code examples
node.jscanvaswebpnode-canvas

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


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.


Solution

  • 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` };
        });