0

As titled,

I have the following piece of code which is written on NextJS API, which is to edit the images accordingly in canvas (using node-canvas for this) before sending it to another API for further processing.

/* At sample.js in NextJS API */
import axios from 'axios';
import { loadImage } from 'canvas';
import FormData from 'form-data';

export default (req, res) => {
    const { source } = req.body;

    /* Something in here */

    loadImage(source).then(async image => {
    let cvs = createCanvas(),
        ctx = cvs.getContext('2d'),
        iWidth = image.naturalWidth,
        iHeight = image.naturalHeight;

    /* Some edit happening here to image */

      ctx.drawImage(
        image,
        0,
        0,
        iWidth,
        iHeight,
        0,
        0,
        w,
        h
      );

      let resizedb64 = cvs.toDataURL();
      let trimmedB64 = resizedb64.replace(/^data:image\/[a-z]+;base64,/, '');

      const fd = new FormData();
      fd.append('file', trimmedb64);

      const opts = {
        method: 'POST',
        url: pathToAnotherAPIHere,
        headers: fd.getHeaders(),
        data: fd
      };

      let promise = await axios(opts); 
  });
}

So the above can work if the destination API accepts base64 image.. but what about if the destination API accepts only binary file? Is there a way to convert the base64 to binary file? From what i read, the only way to get this done in NodeJs is to write the base64 as file first using fs before reading the file again as binary, but that seems troublesome to me, and i don't fully understand the need for that.

Thanks

Fred A
  • 1,602
  • 1
  • 24
  • 41
  • Use the function btoa() – John Dec 03 '20 at 06:58
  • @John I think you meant function atob() I don't know the caniuse for node.js ... node-fetch may also be helpful ... https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript – Wayne Dec 03 '20 at 07:05
  • @Wayne yea, its the reverse, atob. – John Dec 03 '20 at 07:07

1 Answers1

2

Don't convert to a data URL, go directly to a Buffer using node-canvas toBuffer() method.

Then you can use this Buffer with form-data directly.

const buf = canvas.toBuffer();
fd.append('file', buf);
Kaiido
  • 123,334
  • 13
  • 219
  • 285