In previous I mentioned how to Convert seconds to hh:mm:ss using Javascript but in this article, I have mentioned how we can convert any image(png, jpeg etc) to base64 in JS (Javascript) using various possible methods.

Method 1 (Using FileReader)

In this method, we will upload local file using input type= file and then once file selected, we will call our function to load image in FileReader object and then read use readAsDataURL to get base64 string from png or jpeg or svg type images.

So, here is the sample Javascript function for that:

      var base64String = "";
      function FileUpload() {
         var file = document.querySelector(
         var reader = new FileReader();
         reader.onload = function () {
            base64String = reader.result.replace("data:", "")
            .replace(/^.+,/, "");
      function display() {
        document.getElementById("base64string").innerHTML = base64String;

and here is the sample HTML:

 <input type="file" name="" id="fileId" 
    <button onclick="display()">
        Display String
    <div id="base64string">

and here is the working sample output:


and here is the working fiddle:

For upload local images and converting to base64 to save it in database, it is good to use this approach.

Method 2 (By Creating Canvas element)

We can also convert image to base64, by creating canvas element dynamically using JS, once image is loaded in Image() object, and then call canvas.toDataURL to get base64 string.

Here is the sample Javascript code:

<img src="">
      function toBase64(src, callback){
         var image = new Image();
         image.crossOrigin = 'Anonymous';
         image.onload = function(){
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            canvas.height = this.naturalHeight;
            canvas.width = this.naturalWidth;
            context.drawImage(this, 0, 0);
            var dataURL = canvas.toDataURL('image/jpeg');
         image.src = src;
      toBase64('', function(dataURL){

and working fiddle here:

You can use this method to convert any image type to base-64, here are supported formats list.

image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx.

You may also like to read:

Word count using Javascript (jQuery or Pure JS)

Creating copy to clipboard using Javascript or jQuery

String to Number (Int) using Javascript

Convert EPOC (Unix) time stamp to Datetime and Vice-Versa in C#

Top Amazon EC2 Alternatives

Bootstrap alternatives

Best AWS S3 Free Alternatives