How To Convert Image To The Base64 String

In this blog, I am going to explain you the below two concepts. I will be using jQuery, AJAX, SQL Server, and ASP.NET technologies. 1. How to convert an image to the base64 string and save to the database. 2. Display image on the webpage from the base64 string.

In this blog, I am going to explain the below two concepts. I will be using jQuery, AJAX, SQL Server, and ASP.NET technologies.

  1. How to convert an image to the base64 string and save it to the database.
  2. Display image on the webpage from the base64 string.

How to convert an image to the base64 string using jQuery?

  1. Open Visual Studio X (X=version).

  2. Create a new web application. In my case, the name of the application is “SaveImageBase64” as you can see in the below picture (Figure:-1).

  3. Add one web page to your application and give the name to it according to your convenience. 

     
    Figure-1

  4. Add the jQuery library to your web page.

  5. Add an HTML control to your web application to browse the file as given below.
    1. <input type="file" onchange="encodeImageFileAsURL(this)" />  
    As you can see above, there is a function which will be called on onchangeevent .

  6. Add the given below JavaScript code to your webpage.

     

    1. var imagebase64 = "";  
    2.   
    3. function encodeImageFileAsURL(element) {  
    4.     var file = element.files[0];  
    5.     var reader = new FileReader();  
    6.     reader.onloadend = function() {  
    7.         imagebase64 = reader.result;  
    8.     }  
    9.     reader.readAsDataURL(file);  
    10. }  
    In the above code, the variable “imagebase64” contains the base64 value of the browsed image.

  7. Now, you can simply store the base64 string value to your database in the form of a string.

How to display image using base64 string.

You can simply assign the base64 string to image source as I have done below.

  1. <imgsrc=”base64string”>  

To download this application, please visit the below link.