Created
April 22, 2018 15:54
-
-
Save iinsta/917670c668b1ee39d3d746286e7d7852 to your computer and use it in GitHub Desktop.
Download photos with EXIF data in browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var piexif = require('piexif'); | |
/* usage: | |
downloadPictureWithEXIFandRename('https://images.unsplash.com/photo-1502120492606-fba13cc63721?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=289f912c1f9e61361e64ac022a2a6ccc&auto=format&fit=crop&w=668&q=80', 'hello!') | |
*/ | |
function downloadPictureWithEXIFandRename(pictureUrl, pictureName, callback) { | |
var xhr = new XMLHttpRequest(); | |
var a = document.createElement('a'); | |
xhr.responseType = "arraybuffer"; | |
xhr.open('GET', pictureUrl, true); | |
xhr.onload = function () { //image/jpeg | |
var base64_imgdata = arrayBufferToBase64(xhr.response); | |
var exifimg = 'data:image/jpeg;base64,' + base64_imgdata; | |
var exif = piexif.load(exifimg); | |
var exifModified = piexif.insert(piexif.dump(exif), exifimg); | |
var file = b64toBlob(exifModified.replace('data:image/jpeg;base64,', ''), 'image/jpeg') | |
a.href = window.URL.createObjectURL(file); | |
a.download = pictureName; // Set to whatever file name you want | |
// Now just click the link you created | |
// Note that you may have to append the a element to the body somewhere | |
// for this to work in Firefox | |
a.click(); | |
a=null;xhr=null; | |
callback && callback(); | |
} | |
xhr.send() | |
} | |
function arrayBufferToBase64( buffer ) { | |
var binary = ''; | |
var bytes = new Uint8Array( buffer ); | |
var len = bytes.byteLength; | |
for (var i = 0; i < len; i++) { | |
binary += String.fromCharCode( bytes[ i ] ); | |
} | |
return window.btoa( binary ); | |
} | |
function b64toBlob(b64Data, contentType, sliceSize) { | |
contentType = contentType || ''; | |
sliceSize = sliceSize || 512; | |
var byteCharacters = atob(b64Data); | |
var byteArrays = []; | |
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { | |
var slice = byteCharacters.slice(offset, offset + sliceSize); | |
var byteNumbers = new Array(slice.length); | |
for (var i = 0; i < slice.length; i++) { | |
byteNumbers[i] = slice.charCodeAt(i); | |
} | |
var byteArray = new Uint8Array(byteNumbers); | |
byteArrays.push(byteArray); | |
} | |
var blob = new Blob(byteArrays, { type: contentType }); | |
return blob; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment