Sadra Babaei
Sadra Babaei

Reputation: 39

Save img tag in local disk in javascript

I would like to store image of base64 type.

Save to local drive.

For example save in c:\temp\image.png

// Image type base64
var images = $('.cropme img').attr('src');

Upvotes: 1

Views: 20823

Answers (3)

ANR Upgraded Version
ANR Upgraded Version

Reputation: 949

Try this..

<script>
 var imagedata="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/..";
 document.getElementById('img').setAttribute( 'src',imagedata);
 document.getElementById('anchor').setAttribute( 'href',imagedata);
</script>

Working Example Here

Upvotes: 0

orcaman
orcaman

Reputation: 6551

This is how you do it:

var save = document.createElement('a');
save.href = $('#myImageID').attr('src');
save.target = '_blank';
save.download = 'photo.jpg'

var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);

You need to trigger this code from a user gesture (e.g. click on a button).

Upvotes: 3

AkshayJ
AkshayJ

Reputation: 769

Assign the image source to base64 string as follows-->

document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' );

Here you go,on right click on this image you can save it to your local drive easily. :)

If you want to download it onclick of button you have to use html5 download attribute as show here http://jsfiddle.net/3EjUg/5/

Upvotes: -1

Related Questions