Googlebot
Googlebot

Reputation: 15683

How to save image by JavaScript (from browser)

Consider an image loaded as

<img src="https://www.example.com/image.jpg" />

How can I add a save button to save the image from the browser loaded image instead of connecting to the server again to download the image from src.

document.getElementById("save").addEventListener("click", 
function(){
// Save the image from the browser cache without connecting to the server again
});

In fact, I want to mimic the browser's Save image as...

For example, imagine the image is very large. I do not want to transfer the image data again. I want to save the loaded image, as Save image as... in Chrome does.

Upvotes: 2

Views: 6605

Answers (1)

motia
motia

Reputation: 1999

In this example I fetched the image through a XMLHttpRequest request then used the raw image as a data url.

 // credit to https://www.tutorialspoint.com/How-to-convert-the-image-into-a-base64-string-using-JavaScript

function toDataURL(url, callback) {
       var httpRequest = new XMLHttpRequest();
       httpRequest.onload = function() {
          var fileReader = new FileReader();
             fileReader.onloadend = function() {
                callback(fileReader.result);
             }
             fileReader.readAsDataURL(httpRequest.response);
       };
       httpRequest.open('GET', url);
       httpRequest.responseType = 'blob';
       httpRequest.send();
    }
    toDataURL(
       'http://placehold.it/512x512',
        function(dataUrl) {
          document.write('<a href="'+dataUrl+'" download>Save as</a><img src="'+dataUrl+'"></a>');
       }
    )

Upvotes: 1

Related Questions