Created
November 4, 2019 06:58
-
-
Save j0nathanB/5646bfb2754e65293a10ef7f85025514 to your computer and use it in GitHub Desktop.
// gets a stream of images, reads the exif data, and adjusts orientation appropriately
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
| // gets a stream of images, reads the exif data, and adjusts orientation appropriately | |
| // piexif: https://github.com/hMatoba/piexifjs | |
| var imgs = document.querySelectorAll("img") | |
| // main part | |
| imgs.forEach( img => { | |
| toDataURL(img.src) | |
| .then( xhr => resToBlob(xhr.response) ) | |
| .then( blob => { | |
| img = rotateImage(img, blob) | |
| img.onerror = loadFailure; | |
| } ) | |
| }) | |
| // piexif requires jpegData must be a string that starts with "data:image/jpeg;base64," | |
| function resToBlob(res) { | |
| var fr = new FileReader(); | |
| return new Promise(function (resolve, reject){ | |
| fr.onload = function(){ | |
| resolve(piexif.load(this.result)) | |
| }; | |
| fr.readAsDataURL(res); | |
| }) | |
| } | |
| // adapted from: https://stackoverflow.com/questions/934012/get-image-data-url-in-javascript/42916772#42916772 | |
| function toDataURL(url, callback){ | |
| var xhr = new XMLHttpRequest(); | |
| return new Promise(function (resolve, reject) { | |
| // Setup our listener to process compeleted requests | |
| xhr.onreadystatechange = function () { | |
| // Only run if the request is complete | |
| if (xhr.readyState !== 4) return; | |
| if (xhr.status >= 200 && xhr.status < 300) { | |
| resolve(xhr); | |
| } else { | |
| reject({ | |
| status: xhr.status, | |
| statusText: xhr.statusText | |
| }); | |
| } | |
| }; | |
| xhr.open('get', url); | |
| xhr.responseType = 'blob'; | |
| xhr.send(); | |
| }) | |
| } | |
| function rotateImage(img, blob) { | |
| var orientation = blob["0th"]["274"]; | |
| // integer between 1 and 8 inclusive. see https://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/ | |
| if (orientation === 6) { | |
| img.style.transform = "rotate(90deg)" | |
| } else if (orientation === 8) { | |
| img.style.transform = "rotate(270deg)" | |
| } else if (orientation === 3) { | |
| img.style.transform = "rotate(180deg)" | |
| } | |
| return img; | |
| } | |
| function loadFailure() { | |
| console.log("'" + this.name + "' failed to load."); | |
| return true; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment