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 local storage with $localStorage
of AngularJS?
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 local storage with $localStorage
of AngularJS?
The following function makes a request to get the image data, converts the received data to base 64 using 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 CORS headers are enabled in the image.
Next, the code to save the image in LocalStorage
might look like this:
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 into a <img>
element like this:
var img = document.createElement('img');
img.src = localStorage.getItem('imagem');
document.body.appendChild(img);
Note: It does not work in the OS editor because of restrictions on local storage.
Note 2: code snippets based on in this great article .
The function below retrieves the base64 value of an image in 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 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 old code, except that I changed the name of the element stored in LocalStorage
.
Note: Part of the code was based in this OS issue .