Categories
JavaScript Answers

How to Get Image Data as a Base64 URL in JavaScript?

Spread the love

Sometimes, we may want to get our image data as a base64 URL in our web app.

In this article, we’ll look at how to get image data as a base64 URL in JavaScript.

Putting an Image into a Context and Convert the Canvas Data to Base64

One way to convert an image file into a base64 string is to put it into a canvas.

Then we can call the canvas’s toDataURL method to convert it into a base64 string.

For instance, we can write:

const getBase64Image = (url) => {
  const img = new Image();
  img.setAttribute('crossOrigin', 'anonymous');
  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    const dataURL = canvas.toDataURL("image/png");
    console.log(dataURL)
  }
  img.src = url
}

getBase64Image('https://uploads.sitepoint.com/wp-content/uploads/2015/12/1450377118cors3.png')

We create the getBase64Image function that takes the url string for the URL of the image.

Then we create an img eklement with the Image constructor.

Next, we call seAttribute to set the crossOrigin attribute to anonymous so that we can get images that have domains different from what we have.

Next, we create the img.onload method that creates a canvas elemnt with document.createElement .

Then we set the canvas width and height to the img element’s width and height.

Next, we get the canvas context with getContext .

Then we call drawImage to draw the image on the canvas.

The 2nd and 3rd arguments are the x and y coordinates of the top left corner.

Then we call toDataURL with the MIME type that we want to image to have to convert it to a base64 string version of the image.

Then the console.log should log the base64 URL.

Then we set img.src to the url to trigger the onload method to run.

Therefore, when we run getBase64Image with an image URL, we’ll see the base64 string version of it logged.

Conclusion

We can convert an image to a base64 URL by loading the image with the given URL into the canvas and then call toDataURL to convert it to base64.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *