find and solve || findandsolve.com
Please wait.....

Convert Base64 string to image using JavaScript


Option 1.

Convert an image into Base64 string using JavaScript

function getBase64Image(src, callback, outputFormat) {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        let dataURL;
        canvas.height = img.naturalHeight;
        canvas.width = img.naturalWidth;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
      };
      img.src = src;
      if (img.complete || img.complete === undefined) {
        img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        img.src = src;
      }
    }


Javascript convert image to base64

function encodeImageFileAsURL(element) {
  var file = element.files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    console.log('RESULT', reader.result)
  }
  reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />



Option 2.

 Convert base64 to image

var proImage= new Image();
proImage.src = 'data:image/png;base64,kiDinsil...';
document.body.appendChild(proImage);

Convert an image into Base64 string using js

 function getBase64Image(src, callback, outputFormat) {
      const proImage= new Image();
      proImage.crossOrigin = 'Anonymous';
      proImage.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        let fullURLPIC;
        canvas.height = proImage.naturalHeight;
        canvas.width = proImage.naturalWidth;
        ctx.drawImage(proImage, 0, 0);
        fullURLPIC = canvas.toDataURL(outputFormat);
        callback(fullURLPIC);
      };
      proImage.src = src;
      if (proImage.complete || proImage.complete ==='undefined') {
        proImage.src = "data:image/gif;base64,UDUBADUSADFUKBKJADF///IDFINDFIONOINNDFDFSD==";
        proImage.src = src;
      }
    }


Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response