UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Base 64 image encoding from file Javascript

How can convert Image to base 64 text

by Athil


Posted on 24 Jun 2019 Category: Javascript Views: 113

Edited on 24 Jun 2019


Here I am going to show how to convert an image file to base 64 using javascript.

DEMO

Base 64 code is the text that we can use as a source of image control instead of a physical path.

In this demo you will get a text code that we can use as src attribute of <img> </img>

Example in html

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4Qx8RXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUAAAABAAAAYgEbAAUAAAABAAAAagEoAAMAAAABAAIAAAExAAIAAAAbAAAAcgEyAAIAAAAUAAAAjodpAAQAAAABAAAAogAAAM4AAABIAAAAAQAAAEgAAAABQWRvYmUgUGhvdG9zaG9wIENTIFdpbmRvd3MAADIwMTc6MDU6MzEgMTI6NDc6MTMAAAOg.......

Example in CSS

body {
 background-image: url("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4Qx8RXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUAAAABAAAAYgEbAAUAAAABAAAAagEoAAMAAAABAAIAAAExAAIAAAAbAAAAcgEyAAIAAAAUAAAAjodpAAQAAAABAAAAogAAAM4AAABIAAAAAQAAAEgAAAABQWRvYmUgUGhvdG9zaG9wIENTIFdpbmRvd3MAADIwMTc6MDU6MzEgMTI6NDc6MTMAAAOg.......
}

Demo Full code


<html>
<H1> Base 64 image encoding from file </H1>
<input id="inputFile" type="file" onchange="encodeImage();" />
<div id="imgTest"></div>
<script type='text/javascript'>
  function encodeImage() {

    var fileimage = document.getElementById("inputFile").files;
    if (fileimage.length > 0) {      
      var fileRdr = new FileReader();
      fileRdr.onload = function(fileLoadedEvent) {
        var imageCode = fileLoadedEvent.target.result; // <--- data: base64	    
        document.getElementById('imgLabel').innerHTML = imageCode;			 
      }
      fileRdr.readAsDataURL( fileimage[0]);
    }
  }
</script>


<br/>


<label id="imgLabel" style="max-width: 500px; word-wrap: break-word" >


</html>

 



Leave a Comment:


Advertisement