UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Base 64 Image encoding from file javascript

Code and Demo for converting image to base 64 text and how to use base 64 image text

by Athil


Posted on 06 Feb 2017 Category: Javascript Views: 1016

Edited on 02 Jun 2017


Hi, Here I am going to show how to convert image file to base 64 image using HTML 5 and jquery.  Before that Base 64 image means we can convert image to some text so that we need not want to store as file. We can store image as text and that we can be used in HTML pages.

DEMO

Code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#FileUpload1').change(function () {
                  
                    var rdr = new FileReader();
                    rdr.onload = function (e)
                    {
                      
                        document.getElementById('Image1').setAttribute("src", e.target.result);
                        document.getElementById('divTag').innerHTML = " &lt;img src =\"" + e.target.result + "\" &gt;&lt;/img&gt;";
                    }
                    rdr.readAsDataURL(
                        $(this)[0].files[0]
                       );
            });
        });
    </script>
    <input type="file" id="FileUpload1" accept=".jpg,.png,.gif" />
        <br />
                <img id="Image1"   style="width:250px;height:250px;" alt="" />
        <br/>
         <div id="divTag"> </div>
    </form>

</body>
</html>

Output

You can copy the code to a html page and you will get a image in img tag

<img src ="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAe...........................................BJRU5ErkJggg==" ></img>

 

Use in background style 

.classbg {
    background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAe...................BJRU5ErkJggg==');
}

 

 



Leave a Comment:

                 

Riyas OP Tuesday,16 May 2017

Great article, Usefull

Advertisement