Computer >> Computer tutorials >  >> Programming >> Javascript

How to get image data url in JavaScript?


To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it.

This will return the base64 encoded data URI of the image. For example, if you have an image with id my-image, you can use the following −

Example

function getDataUrl(img) {
   // Create canvas
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');
   // Set width and height
   canvas.width = img.width;
   canvas.height = img.height;
   // Draw the image
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');
}
// Select the image
const img = document.querySelector('#my-image');
img.addEventListener('load', function (event) {
   const dataUrl = getDataUrl(event.currentTarget);
   console.log(dataUrl);
});

Output

This will give the output −

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB