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,
data
- data encoding prefixMediatype
- is a Mimetype string that represents the type of the fileBase64
- Encoding name that represents that the content is encoded in a Base64 stringdata
- Textual representation of the binary file encoded in the Base64 format
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.
-
Image
element is to display the image in the HTML -
Canvas
element is to draw the image from the image element and get the Base64 encoded data
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.
- Get the image element using its
ID
and store it in theimg
variable - Get the canvas element using its
ID
and store it in thecanvasElmt
variable - Get the
2D
context of the canvas element using thegetContext()
element - Using the canvas context, draw the image element into the canvas using the drawImage() method
- Invoke the
toDataURL()
method of the Canvas element. It’ll return the Base64 encoded data of the image drawn in the canvas
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.
Also published here.