I want to get and check the width and height of an uploaded image using ng2-file-upload and Angular 6.
My code so far is:
constructor() {
this.uploader = this.initializeUploader("url");
}
public uploader;
private initializeUploader(url: string): FileUploader {
const uploadOptions: FileUploaderOptions = {
allowedMimeType: ['image/jpeg', 'image/png' ],
}
const uploader = new FileUploader(uploadOptions);
uploader.onAfterAddingFile = item => {
console.log(item);
//Want to get width here
}
return uploader;
}
and the HTML:
<input type="file" ng2FileSelect [uploader]="uploader" />
I was looking for solutions but nothing worked for me. Found the idea to use
Upload.imageDimensions(file).then()
here. But i don't understand how/where to import 'Upload'. Also found the solution to add
ngf-min-height="1"
in the input-element but i can't find where i can "catch" the error, if the size of the input image is wrong.
Transform your file to a base64, and create an image with that base as the source. During the load
hook, you can get the size of the image. Here is a working snippet !
function change() {
const input = document.querySelector('input');
const file = input.files[0];
getBase64(file).then(base64 => {
const img = new Image();
img.onload = () => console.log(img.width, img.height);
img.src = base64;
});
}
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
<input type="file" onchange="change()">