Converting an image into data URI using JavaScript FileReader

I have noticed that more and more sites are using data URL for images instead of image URL.

When using data URIs, we don't have to link external image file, instead we can directly embed the image data into the document using data URIs.

For example

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA..................L2E4wxR0DDAAAAAElFTkSuQmCC" />


The above code will print the following image



The format of data URIs are
data:[MIME-TYPE][;CHARSET=<encoding>][;base64];<data>


Using data URIs have various advantages, like extra HTTP request is not required and LESS HTTP REQUEST = BETTER and they are very faster for small files.

We can convert image into data URIs in browser it self using FileReader.

Let code explain you how to convert the image to base64 data URI
<html>
<head>
<title>Converting Image to Data URIs in JavaScript</title>
</head>
<body>
	Select Image file
	<input type="file" id="files" multiple />
	<div id="fileContent"></div>
</body>
<script>

function fileSelected(evt) {
    var files = evt.target.files;
	var type = '';
	var fr = new FileReader();
	fr.onload = function(event)
	{
		if(type.indexOf("image") == 0){
			document.getElementById('fileContent').innerHTML = "<img src='" + event.target.result + "' />";
			document.getElementById('fileContent').innerHTML += "<br/>";
			var d = event.target.result;
			d = d.replace("data:;","data:" + type + ";");
			document.getElementById('fileContent').innerHTML += "<strong>Data URI: </strong>" + d;
		}
	}
	
    for (var i = 0, f; f = files[i]; i++) {
      
	  //Gives name of file : f.name
	  //Gives type of file : f.type e.g. text/plain or image/png etc
	  //Gives size of file : f.size (in bytes)
	  //Gives last modified date : f.lastModifiedDate
	  
	  var fileCopy = f.slice(0, f.size); //i.e. read entire file, as reading half image file doesn't solve any purpose
	  
	  type = f.type;
	if(f.type.indexOf("image") == 0)
		fr.readAsDataURL(fileCopy); //on successful read, fr.onload function will be called and that will populate the result in fileContent container
    }
  }
  
  //attach change event of file control
  document.getElementById('files').addEventListener('change', fileSelected, false);
</script>
</html>


Try converting an Image into data URI here

Select Image file
Add Comments :

Frank Goortani 21 Sep 15

Thanks! This is useful! 

aTool 31 May 15

http://www.atool.org/img2base64.php

Login

Register