How to Convert Image into Base64 String using Jquery?

jquery , JavaScript

Nicesnippets

5339

27-12-2019


Hi Dev,

In this blog, I will learn you how to convert image into base64 string using jquery. You can upload image in base64 string into database using jquery.

This example helps you how to convert images into base 64 string using jQuery/javascript. and Display image base64 string to on webpage.

Example 1 : Convert image to base64 string jQuery

<!DOCTYPE html>

<html>

<head>

<title>jQuery Convert image into base64 string</title>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

</head>

<body>

<form>

<input type="file" name="img" id="image" onchange="encodeImgtoBase64(this)">

<button type="submit">Submit</button>

<a id="convertImg" href=""></a>

</form>

</body>

<script type="text/javascript">

function encodeImgtoBase64(element) {

var img = element.files[0];

var reader = new FileReader();

reader.onloadend = function() {

$("#convertImg").attr("href",reader.result);

$("#convertImg").text(reader.result);

}

reader.readAsDataURL(img);

}

</script>

</html>

Example 2 : jQuery Convert Image base64 string & display image

In this example, You will convert image to base64 string and display image on the page

<!DOCTYPE html>

<html>

<head>

<title>jQuery convert image into base64 string and display image</title>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

</head>

<body>

<form>

<input type="file" name="img" id="img" onchange="encodeImgtoBase64(this)">

<button type="submit">Submit</button>

<a id="convertImg" href=""></a>

<br>

<img src="" alt="" id="displayImg" width="500">

</form>

</body>

<script type="text/javascript">

function encodeImgtoBase64(element) {

var img = element.files[0];

var reader = new FileReader();

reader.onloadend = function() {

$("#convertImg").attr("href",reader.result);

$("#convertImg").text(reader.result);

$("#displayImg").attr("src", reader.result);

}

reader.readAsDataURL(img);

}

</script>

</html>

It will help you...


Recommended Posts