How to put an image file in a JSON object with JavaScript?

To put an image file in a JSON object with JavaScript, we convert it to a data URI.

For instance, we write

const convertToDataURLviaCanvas = (url, callback, outputFormat) => {
  const img = new Image();
  img.crossOrigin = "Anonymous";
  img.onload = () => {
    const canvas = document.createElement("CANVAS");
    const ctx = canvas.getContext("2d");
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);
    const dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = url;
};

convertToDataURLviaCanvas("http://bit.ly/18g0VNp", (base64Img) => {
  //...
});

to define the convertToDataURLviaCanvas function.

In it, we create an img element with the Image constructor.

Then we set its onload property to a function that creates a canvas with createElement.

Then we call getContext to get the context object.

We call drawImage to draw the image onto the canvas.

And we get the base64 data URI with toDataURL.

We then load the image with the url by setting the src property.

Next, we call convertToDataURLviaCanvas with the image URL and a callback that has the base 64 URI string in the base64Img parameter.