Saving Image as Data using dataURI

By using a method called “Data URI Scheme”, images can be directly embedded in HTML files. An image is converted to data uring base64 encoding, the data is appended in the page, which works as the image itself.

What is Data URI Scheme?

The data URI scheme is a URI scheme (Uniform Resource Identifier scheme) that provides a way to include data in-line in web pages as if they were external resources.

Using the method of Data URI, this post here presents a way to store locally using the HTML5 localstorage.
Here is a function which accepts the url path of the image and converts it into binary data. The binary data is then stored in the local storage.

function GetBase64Image:(URL,StorageKey) {
					   var img = new Image();
					    img.src = URL;
					    img.onload = function () {

					    var canvas = document.createElement("canvas");
					    canvas.width =this.width;
					    canvas.height =this.height;

					    var ctx = canvas.getContext("2d");
					    ctx.drawImage(this, 0, 0);


					    var dataURL = canvas.toDataURL("image/png");

					    localStorage.setItem(StorageKey,dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
					    

					    }

Now here is the simple code snippet which checks if the image is loaded into the local storage and retrieve locally if available. If it is not available in the localstorage, the path is used to again create the binary data using the encoding technique.

var logoimage=logourl;
			
		
			if(localStorage.getItem("logo")!=null && localStorage.getItem("logo")!="null")
			{

				$('#imgLogo').attr("src","data:image/png;base64, "+localStorage.getItem("logo"));								
			}
			else
			{
				$('#imgLogo').attr("src",logoimage);						
				GetBase64Image(footerlogo,"logo");
				
			}
			

Facebook Facebook LinkedIn LinkedIn

Leave a Comment

For Gravatar icon