Skip to content

Instantly share code, notes, and snippets.

@gracefullight
Last active December 1, 2017 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gracefullight/6e78b0ef7d6eb7acd989f7e3d85ae158 to your computer and use it in GitHub Desktop.
Save gracefullight/6e78b0ef7d6eb7acd989f7e3d85ae158 to your computer and use it in GitHub Desktop.
/**
* [downloadImage]
* @param {[string]} img [base64encoded image data]
* @param {[string]} fileName [new file name]
* @return [image file]
*/
function downloadImage(img, fileName) {
var imgData = atob(img.src.split(',')[1]),
len = imgData.length,
buf = new ArrayBuffer(len),
view = new Uint8Array(buf),
blob,
i;
for (i = 0; i < len; i++) {
view[i] = imgData.charCodeAt(i) & 0xff; // masking
}
blob = new Blob([view], {
type: 'application/octet-stream'
});
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
//var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.style = "display: none";
//a.href = url;
a.href = img.src;
a.download = fileName;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
//URL.revokeObjectURL(url);
}, 100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment