Base64 text represents binary files such as images in text format. It is designed to binary format data across channels that support only text format, such as email applications.

This tutorial will teach you how to get Base64 encoded data from an HTML image element in JavaScript.

The image element displays static images in HTML, whereas Canvas uses JavaScript to draw graphics into it.

The Canvas also provides an API method toDataURL() to get the Base64 data of the image drawn on the canvas element.

Base64 String Format

Base64 strings are in a text format; sometimes, it has a metadata prefix. When it has a Metadata prefix, it is known as DataURL.

Syntax

data:[<mediatype>][;base64],<data>

Where,

Example

data:image/png;base64,<Base64 String>

The above string represents a Base64 string of a PNG image.

Let us see how to get the Data URL of the image displayed in the HTML image.

HTML Code

Let us create an HTML page with an image and Canvas elements.

Code

<img id="imgElement" src="https://picsum.photos/200">

<canvas id="canvasElement" />

Output

Using Canva and toDataURL() Method to Get Base64 Encoded Data

This section teaches you how to get the Base64 encoded data from the Canvas element using the toDataURL() method in JavaScript.

Code


var img = document.getElementById("imgElement");

var canvasElmt = document.getElementById("canvasElement");

var ctx = canvasElmt.getContext("2d");

ctx.drawImage(img, 10 ,10);

console.log(canvasElmt.toDataURL());

Output

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAAAXNSR0IArs4c6QAABGJJREFUeF7t1AEJAA=="

Conclusion

In this tutorial, you’ve learned how to get the Base64 encoded data of an Image displayed in the HTML image element by drawing it into the canvas element.