How to Convert Image into Base64 String using Jquery?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share
How to Convert Image into Base64 String using Jquery

Today now in this blog, I will show you how to convert image into base64 string by using jquery. So here we can upload image in base64 string into database by using jquery.

On this example will help you to know how to convert images into base 64 string by using jQuery/javascript. and also Display image base64 string to on your 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

Now in this example, we 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>

Read also : How To Set Bcc And Cc Mail Address In Laravel Mail?

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →