Image rotation on input type="file"
You should take a look at the modern javascript library JavaScript-Load-Image that has already a complete solution to the EXIF orientation included the auto-fix.
You could use the image scaling (.scale()
method) to convert the image to the canvas and fix your image orientation.
Take a look to Fix image orientation with Javascript.
Here is another interesting lib : react-exif-orientation-img
Here the adaptation of the solution @German Plebani menitioned in comments for your needs:
import React, {Component} from "react";
import FileUploader from "react-firebase-file-uploader";
import exif from 'exif-js';
function readFile(file) {
return new Promise(resolve => {
var reader = new FileReader();
reader.onload = e => resolve(e.target.result);
reader.readAsDataURL(file);
});
};
function createImage(data) {
return new Promise(resolve => {
const img = document.createElement('img');
img.onload = () => resolve(img);
img.src = data;
})
}
function rotate(type, img) {
return new Promise(resolve => {
const canvas = document.createElement('canvas');
exif.getData(img, function () {
var orientation = exif.getAllTags(this).Orientation;
if ([5, 6, 7, 8].indexOf(orientation) > -1) {
canvas.width = img.height;
canvas.height = img.width;
} else {
canvas.width = img.width;
canvas.height = img.height;
}
var ctx = canvas.getContext("2d");
switch (orientation) {
case 2:
ctx.transform(-1, 0, 0, 1, img.width, 0);
break;
case 3:
ctx.transform(-1, 0, 0, -1, img.width, img.height);
break;
case 4:
ctx.transform(1, 0, 0, -1, 0, img.height);
break;
case 5:
ctx.transform(0, 1, 1, 0, 0, 0);
break;
case 6:
ctx.transform(0, 1, -1, 0, img.height, 0);
break;
case 7:
ctx.transform(0, -1, -1, 0, img.height, img.width);
break;
case 8:
ctx.transform(0, -1, 1, 0, 0, img.width);
break;
default:
ctx.transform(1, 0, 0, 1, 0, 0);
}
ctx.drawImage(img, 0, 0, img.width, img.height);
ctx.toBlob(resolve, type);
});
})
}
class OrientationAwareFirebaseImageUploader extends Component {
handleChange = (event) => {
event.target.files.forEach(
file => readFile(file)
.then(createImage)
.then(rotate.bind(undefined, file.type))
.then(blob => {
blob.name = file.name;
this.uploader.startUpload(blob);
})
);
}
render() {
return (
<FileUploader
{...this.props}
ref={ref => this.uploader = ref}
onChange={this.handleChange}
accept="image/*"
/>
);
}
}
export default OrientationAwareFirebaseImageUploader;