Created
September 6, 2022 11:53
-
-
Save caroillemann/ab7ca13d347452376f6099bcc3099ccc to your computer and use it in GitHub Desktop.
Fix jpg image orientation on client-side by reading exif data
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
import loadImage from 'blueimp-load-image' | |
/** | |
* Fix jpg image orientation on client-side by reading exif data - inspired by: https://stackoverflow.com/a/56268674/10280454 | |
* @param {file} file - Files to upload | |
* @return {file} - The file with the right orientation without exif data | |
*/ | |
const fixExifOrientation = async file => { | |
const jpegTypes = ['image/jpg', 'image/jpeg'] | |
if (jpegTypes.includes(file.type)) { | |
// STEP 1: Read image file and return as canvas with the properly oriented image (based on exif orientation data) | |
let data = await loadImage(file, { canvas: true }) | |
const canvas = data.image | |
// const canvasEl = document.body.appendChild(canvas) // FOR DEV - render on screen to check orientation | |
// STEP 2: Convert canvas to data URL (base64) | |
const mimeType = file.type | |
const dataUrl = canvas.toDataURL(mimeType) | |
// STEP 3: Convert data URL to File | |
const fileName = file.name | |
const newFile = dataURLtoFile(dataUrl, fileName, file) | |
file = newFile | |
return file | |
} else { | |
// not jpg --> the file has no useful exif orientation data | |
return file | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment