Save image link as file in Storage location

Asked

Viewed 1,403 times

9

How can I save a link (http://example.com/img.png) in the file format, which in this case is . png, using Javascript and saving in the local $localStorage angularjs?

1 answer

7


Downloading and saving an image

The following function makes a request to get the image data, converts the received data to base 64 using the FileReader and then sends the result to a callback function.

window.URL = window.URL || window.webkitURL;
function downloadImage(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function(e) {
    if (this.status == 200) {
      var reader = new FileReader();
      reader.onload = function (e) {
        callback.call(callbank, e.target.result);
      }
      reader.readAsDataURL(this.response);
    }
  };
  xhr.send();
}

An important note is that if the image is in another domain relative to the script this will only work if the CORS headers are enabled in the image.

Then the code to save the image in the LocalStorage could be so:

downloadImage('https://s3-eu-west-1.amazonaws.com/kienzle.geschaeft/yellow_MarkerA.png', function(base64String) {
  localStorage.setItem('imagem', base64String);
});

And the code to load the image to an element <img> thus:

var img = document.createElement('img');
img.src = localStorage.getItem('imagem');
document.body.appendChild(img);

Functional example in Jsfiddle

Note: does not work in the OS editor due to restrictions in the Storage location.

Note 2: Code snippets based in this excellent article.

Saving an existing image on the current page

The below function recovers the base 64 value of an image on the current page:

function toBase64String(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}

The code to save the image to the LocalStorage is:

localStorage.setItem('minha-imagem', toBase64String(document.getElementById('original')));

And finally, to restore the image:

var img = document.createElement('img');
img.src = localStorage.getItem('minha-imagem');
document.body.appendChild(img);

This is the same code as before, except that I changed the name of the stored element in the LocalStorage.

Functional example in Jsfiddle

Note: part of the code was based in this matter of the OS.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.