JQuery Convert Image to Base64 String Example
When “JQuery Convert Image to Base64 String Example” moves through design, development and browser testing, knowledge management can clarify hand-offs and time spent on revisions while leaving code quality, accessibility and released behaviour as the real measures of success.
For API changes, browser support and current usage patterns, compare the snippet with the official jQuery website before adopting it in production.
Nov 12, 2020
Hi Guys,
Today,I will learn you how to convert image to base64 string in jquery.We will show example of jquery convert image to base64 string.this tutorial helps you how to convert images into base 64 string using jquery or javascript.
1: Convert image to base64 string jQuery
Here,I will show full source code of convert image to base64 string in jQuery/javascript.
<!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="convertImgtoBase64(this)">
<button type="submit">Submit</button>
<a id="convertImg" href=""></a>
</form>
</body>
<script type="text/javascript">
function convertImgtoBase64(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: don’t forget to include the jQuery library on your web page.
The above code will convert your image to base64 string using the jQuery or javascript on the client-side.
2. Convert Image base64 string & display image on the webpage jQuery
Now this example, I will convert image to base64 string and display image on the webpage.
<!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>
It will help you..
- How to Show Loading Spinner in JQuery?
- How to Create Ajax Submit Form Using jQuery?
- How To Get Current Page URL, Path, Host and hash using jQuery?
- How To Get, Set and Delete Div Background Image jQuery?
- JQuery Remove All Unwanted Whitespace From String Example
- Body Background Video Using Vide Jquery Example
- JQuery UI Autocomplete Example
- JQuery Split String By Comma Into Array Example