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