In this blog, I am going to explain the below two concepts. I will be using jQuery, AJAX, SQL Server, and ASP.NET technologies.
- How to convert an image to the base64 string and save it to the database.
- Display image on the webpage from the base64 string.
How to convert an image to the base64 string using jQuery?
- Open Visual Studio X (X=version).
- 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).
- Add one web page to your application and give the name to it according to your convenience.
Figure-1
- Add the jQuery library to your web page.
- Add an HTML control to your web application to browse the file as given below.
- <input type="file" onchange="encodeImageFileAsURL(this)" />
As you can see above, there is a function which will be called on onchangeevent .
- Add the given below JavaScript code to your webpage.
- var imagebase64 = "";
-
- function encodeImageFileAsURL(element) {
- var file = element.files[0];
- var reader = new FileReader();
- reader.onloadend = function() {
- imagebase64 = reader.result;
- }
- reader.readAsDataURL(file);
- }
In the above code, the variable “imagebase64” contains the base64 value of the browsed image.
- 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.
To download this application, please visit the below link.