find and solve ||
Please wait.....

Convert base64 to image javascript and download

I have a base64 string image in my html page now  I want to force the download through JavaScript this image.


Option 1.

Simple you can download your base64 string image like as given below

window.location.href = 'data:application/octet-stream;base64,' + <your  base64 encoded image>;

or if you want to to allow the user to specify a file name, use the download attribute as a tag you can do that 

<a download="FILENAME.EXT" href="data:image/png;base64,your-base64-string-code">Download</a>

Option 2.

var bses64Image= "data:image/" + bses64Image; 
$('#download').attr('href', bses64Image);

Add the file name that you want when downloading to the download tag.

<a download="image-name.png" id="download">download img</a>

Option 3.

There are different types of techniques to download bases64string images, but as a fan of asynchronous programming, I recommend creating a Promise then using the FileReader API to convert the blob:

convertBlobToBase64 = (blob) => new Promise((resolve, reject) => {
    const reader = new FileReader;
    reader.onerror = reject;
    reader.onload = () => {
const base64String = await convertBlobToBase64(blob);

Option 4.

You can also use  this solution.

const base64string = "";
const pageImage = new Image();
pageImage.src = 'data:image/png;base64,' + base64string;
pageImage.onload = function() {
    const canvas = document.createElement('canvas');
    canvas.width = pageImage.naturalWidth;
    canvas.height= pageImage.naturalHeight;
    const ctx = canvas.getContext('2d');
    ctx.imageSmoothingEnabled = false;
    ctx.drawImage(pageImage, 0, 0);   
function saveScreenshot(canvas) {
    let fileName = "image"
    const link = document.createElement('a'); = fileName + '.png';   
    canvas.toBlob(function(blob) {
        link.href = URL.createObjectURL(blob);;

Option 5.

  function downloadBase64File(contentType, base64Data, fileName) {
     const linkSource = `data:${contentType};base64,${base64Data}`;
     const downloadLink = document.createElement("a");
     downloadLink.href = linkSource; = fileName;;

Mahira  khanna

Mahira khanna

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


Report Response