How To Convert Image Into Base64 String Using jQuery

Websolutionstuff | Jan-03-2022 | Categories : jQuery

In this example, we will see how to convert an image into a base64 string using jquery. Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII.

We will convert the image to a base64 string using jquery or javascript. To convert base64 to the string we are using FileReader() function and get the result from the file.

Let's see, convert image to base64 string jquery.

Example  1 : 

FileReader is used to read the contents of a Blob or File.

<!DOCTYPE html>
<html>
  <head>
    <title>How To Convert Image Into Base64 String Using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
  <form>
    <input type="file" name="img" id="image">
    <button type="submit">Submit</button>
    <a id="base64Img" href=""></a>
  </form>
  </body>
  <script type="text/javascript">
    $('#image').on('change', function() {

      var img = element.files[0];
 	
      var reader = new FileReader();
 
      reader.onloadend = function() {
 
        $("#base64Img").attr("href",reader.result);
 
        $("#base64Img").text(reader.result);
      }

      reader.readAsDataURL(img);
    });
  </script>
</html>

 

 

Example 2 :

The createElement() method creates an Element Node with the specified name like button, canvas, etc. 

function base64Img(img) {
   
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');   
   canvas.width = img.width;
   canvas.height = img.height;   
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');
}

const img = document.querySelector('#image');
img.addEventListener('load', function (event) {
   const dataUrl = base64Img(event.currentTarget);
   alert(dataUrl);
});

 


You might also like :

Recommended Post
Featured Post
How To Get Current Date And Time In Vue Js
How To Get Current Date And Ti...

In this article, we will see how to get the current date and time in vue js. In vue js very simple to get the current da...

Read More

Jan-14-2022

Laravel 9 to_route() and str() Helper Function
Laravel 9 to_route() and str()...

In this article, we will see laravel 9 to_route() and str() helper function. The to_route function g...

Read More

Oct-03-2022

Laravel 8 Eloquent orWhereHas Condition
Laravel 8 Eloquent orWhereHas...

In this example we will see laravel 8 eloquent orWhereHas() condition. In previous example we will learn about ...

Read More

Oct-15-2021

jQuery Datatable Hide/Show Column Based On Condition
jQuery Datatable Hide/Show Col...

In this article, we will see a jquery datatable hide/show column based on condition. Here, we will learn how to hide and...

Read More

Jan-26-2023