It is very simple with HTML5 Canvas API, it provides toDataURL() method. The toDataURL() method of the canvas object converts the canvas drawing into a 64 bit encoded PNG URL. We can pass “image/jpeg” as argument to toDataURL() method, to get image data URL in the jpeg format.
Here is the code snippet which explains it:
<!DOCTYPE HTML>
<html>
<head>
<title>Get Image Data URL using JavaScript</title>
</head>
<body>
<script>
var image = new Image();
// create an empty canvas element
var canvas = document.createElement("canvas"),
canvasContext = canvas.getContext("2d");
image.onload = function () {
//Set canvas size is same as the picture
canvas.width = image.width;
canvas.height = image.height;
// draw image into canvas element
canvasContext.drawImage(image, 0, 0, image.width, image.height);
// get canvas contents as a data URL (returns png format by default)
var dataURL = canvas.toDataURL();
document.write(dataURL);
};
image.src = "azure.png";
</script>
</body>
</html>
Dealing with cross domain images:
The toDataURL() method requires that any images drawn onto the canvas should be on the same domain as the code executing it. Otherwise a SECURITY_ERR exception is thrown.
To use toDataURL() method when image is drawn on the canvas loaded from different domain, then we need to set the crossOrigin property of Image object, crossOrigin property of Image object allows two values (anonymous, use-credentials).
var image = new Image();
image.crossOrigin = 'use-credentials';
image.onload = function () {
//.....
}
image.src = "http://www.w3.org/2008/site/images/logo-w3c-screen-lg";
//(or)
var image = new Image();
image.crossOrigin = 'anonymous';
image.onload = function () {
//.....
}
More information on CORS enabled image @ Mozilla DEV Network.