Skip to content

Instantly share code, notes, and snippets.

@caroillemann
Created September 6, 2022 11:53
Show Gist options
  • Save caroillemann/ab7ca13d347452376f6099bcc3099ccc to your computer and use it in GitHub Desktop.
Save caroillemann/ab7ca13d347452376f6099bcc3099ccc to your computer and use it in GitHub Desktop.
Fix jpg image orientation on client-side by reading exif data
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