How to convert data URL to image data with JavaScript?

Sometimes, we want to convert data URL to image data with JavaScript.

In this article, we’ll look at how to convert data URL to image data with JavaScript.

How to convert data URL to image data with JavaScript?

To convert data URL to image data with JavaScript, we can create a canvas with the image.

For instance, we write:

const convertURIToImageData = (url) => {
  return new Promise((resolve, reject) => {
    if (!url) {
      return reject();
    }
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    const image = new Image();
    image.onload = () => {
      canvas.width = image.width;
      canvas.height = image.height;
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
      resolve(context.getImageData(0, 0, canvas.width, canvas.height));
    }
    image.crossOrigin = "Anonymous";
    image.src = url;
  });
}
const url = "https://picsum.photos/200/300";
const load = async () => {
  const img = await convertURIToImageData(url)
  console.log(img)
}
load()

to create the convertURIToImageData function that takes a url.

In it, we return a promise that checks if the url is set.

If it’s not, we reject the promise.

Otherwise, we create a canvas with createElement.

Then we get its context with getContext.

Next, we create an img element with the Image constructor.

We set image.onload to a function to draws the image in the canvas bvy setting the canvas’ size to the image size.

Then we call drawImage to draw the image.

And then we call resolve with the image data we get from getImageData.

Next, we set image.crossOrigin to 'Anonymous' to let us get data from cross domain images.

And we src to url to load the image.

onload runs when the image is loaded.

Next, we define the load function that calls convertURIToImageData with url.

And then we get the img data from the promise with await.

Conclusion

To convert data URL to image data with JavaScript, we can create a canvas with the image.