Convert image into base64 string using jQuery; Through this tutorial, i am going to show you how to convert image into base64 string.
In this tutoria, i will help you how to convert images into base 64 string using jQuery or javascript.
How to Convert Image to Base64 String using jQuery
There are two ways to convert image into base64 string using jquery; as shown below:
- 1. Convert image to base64 string jQuery
- 2. Convert Image base64 string & display image on the webpage jQuery
1. Convert image to base64 string jQuery
See the following example for convert image to base64 string in jQuery/javascript; as shown below:
<!DOCTYPE html> <html> <head> <title>Convert image into base64 string using jQuery</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head> <body> <form> <input type="file" name="file" id="file" onchange="encodeImgtoBase64(this)"> <button type="submit">Submit</button> <a id="convertImg" href=""></a> </form> </body> <script type="text/javascript"> function encodeImgtoBase64(element) { var file = element.files[0]; var reader = new FileReader(); reader.onloadend = function() { $("#convertImg").attr("href",reader.result); $("#convertImg").text(reader.result); } reader.readAsDataURL(file); } </script> </html>
Note that; please include the jQuery library into your file.
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
2. Convert Image base64 string & display image on the webpage jQuery
See the following example for convert image to base64 string and display image on the webpage; as shown below:
<!DOCTYPE html> <html> <head> <title>Convert image into base64 string using jQuery</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head> <body> <form> <input type="file" name="file" id="file" onchange="encodeImgtoBase64(this)"> <button type="submit">Submit</button> <a id="convertImg" href=""></a> <br> <img src="" alt="" id="base64Img" width="500"> </form> </body> <script type="text/javascript"> function encodeImgtoBase64(element) { var file = element.files[0]; var reader = new FileReader(); reader.onloadend = function() { $("#convertImg").attr("href",reader.result); $("#convertImg").text(reader.result); $("#base64Img").attr("src", reader.result); } reader.readAsDataURL(file); } </script> </html>
Recommended jQuery Tutorial
Recommended:-jQuery scrollTop Method
Recommended:-jQuery Load External Html Content from Another Page
Recommended:-jQuery Ajax Post Example
Recommended:-jQuery Get/Find Closets Element
Recommended:-jQuery Check Uncheck Checkbox
Recommended:-jQuery Previous Next Sibling Methods
Recommended:-jQuery setInterval and setTimeout
Recommended:-jQuery Select Multiple Classes
Recommended:-jQuery Registration Form validation using Validator
Recommended:-jQuery Form Validation Custom Error Message
Recommended:-jQuery Get Set and Delete Div Background Image
Recommended:-jQuery Get Current Page URL, Path, Host and hash