How can I fix the EXIF orientation in Angular 2? I am loading an image from mobile and I need to fix the orientation.
I have tried the solution for this post: Component inputs by reference but FileReaderEvent type is not recognised by typescript, EXIF does not exist, and I can't access to the imageRotateDegrees, ImageExifRotation... properties.
This is my code:
imageChange(input){
if (input.files.length > 0) {
var img = document.createElement("img");
img.src = window.URL.createObjectURL(input.files[0]);
// Create a FileReader
var reader = new FileReader();
var self = this;
reader.onload = function (e: any) {
img.onload = function() {
var resizedImg = self.resize(img);
self.model.base64Image = resizedImg;
self.picture = resizedImg;
}
img.src = e.target.result;
}
reader.readAsDataURL(input.files[0])
}
}
I found an Angular library for the problem https://github.com/bergben/ng2-img-max#readme and made it work for me with the following code:
initInputChangeListener() {
const fileInput = document.getElementById('imageFileInput');
if (fileInput) {
fileInput.addEventListener('change', (e: any) => {
if (e.target.files && e.target.files[0]) {
const fileReader = new FileReader();
fileReader.onload = () => {
setTimeout(() => {
this.base64Image = fileReader.result;
// not sure if you need this
// but i had problems without this line of code
});
setTimeout(() => {
let myImage: HTMLImageElement = new Image();
myImage.src = fileReader.result;
this.ng2ImgMaxService.getEXIFOrientedImage(myImage)
.then(result => {
console.log('received getEXIFOrientedImage result');
let canvas =
<HTMLCanvasElement> document.getElementById('myCanvas');
let context = canvas.getContext('2d');
let ratio = result.width / result.height;
let w = result.width - 100;
let h = (w / ratio);
canvas.width = w;
canvas.height = h;
context.drawImage(result, 0, 0, w, h);
let dataUrl = canvas.toDataURL('image/jpeg');
setTimeout(() => {
console.log('updating the image...');
this.base64Image = dataUrl;
});
}, error => {
console.warn(error);
});
});
};
fileReader.readAsDataURL(e.target.files[0]);
}
});
}
}
inside from my template i used:
<img [src]="base64Image" />
<canvas id="myCanvas" style="display: none;"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With