How do I download image from img tag with base64 string in JavaScript?

Stevan
Stevan
Member
310 Points
20 Posts

I have img tag with base64 string as:

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ------------">

on button click wan to download image:

<button class="btn" onclick="downloadImage();"><i class="fa fa-download"></i> download</button>

How do I download image from img tag with base64 string in JavaScript?

Views: 667
Total Answered: 2
Total Marked As Answer: 2
Posted On: 11-Jul-2023 23:10

Share:   fb twitter linkedin
Answers
beginer
beginer
Member
1328 Points
43 Posts
         

Use something:

var a = document.createElement("a"); //Create <a>
a.href = "data:image/png;base64," + ImageBase64; //Image Base64 Goes here
a.download = "Image.png"; //File name Here
a.click(); //Downloaded file
Posted On: 13-Jul-2023 02:41
Raj
Raj
Member
496 Points
21 Posts
         

Try following method:

function downloadImage() {
            var base64String = $("#imageid").attr('src');
            var imageType = base64String.match(/[^:/]\w+(?=;|,)/)[0];
            var a = document.createElement("a");
            a.href = base64String;
            a.download = "Image." + imageType;
            a.click();
        }
Posted On: 13-Jul-2023 03:03
Thanks.
 - Linux U  04-Oct-2023 22:55
 Log In to Chat