Reputation: 563
I'm currently working on an angular web app, and of the features is the photo upload.
I would like to implement validation on the image size so that I can throw errors if the image is too small.
Here is my code:
public onImageDrop(evt: any) {
evt.stopPropagation();
evt.preventDefault();
this.croppieImage = null;
this.onCropeMode = true;
const image: HTMLImageElement = new Image();
const file: File = evt.dataTransfer.files[0];
const myReader: FileReader = new FileReader();
myReader.onloadend = ((loadEvent: any) => {
image.src = loadEvent.target.result;
this.croppieImage = myReader.result;
});
myReader.readAsDataURL(file);
**console.log(image.height);
console.log(image.width);**
this.photoInDragMode = false;
this.uplodedPhotoFileName = file.name;
this.uplodedPhotoFileMimeType = file.type;
this.showPhotoSaveButton = true;
this.onCropeMode = true;
}
The problem I have is that the
console.log(image.height);
console.log(image.width);
Always shows me
> 0
> 0
I really appreciate if anyone can help.
Thanks in advance guys.
Upvotes: 3
Views: 14716
Reputation: 330
HTML
<input type='file'
formControlName="img_name"
class="form-control"
(change)="readUrl($event)">
TS
readUrl(event: any) {
if (event.target.files && event.target.files[0]) {
if (event.target.files[0].type === 'image/jpeg' ||
event.target.files[0].type === 'image/png' ||
event.target.files[0].type ==='image/jpg') {
if (event.target.files[0].size < 200 * 200) {/* Checking height * width*/ }
if (event.target.files[0].size < 2000000) {/* checking size here - 2MB */ }
}
}
Upvotes: 4
Reputation: 574
You get 0 because the image was not loaded yet when you place the console logs. It's loaded in
myReader.onloadend = ((loadEvent: any) => {
image.src = loadEvent.target.result;
this.croppieImage = myReader.result;
});
so you can do something like
myReader.onloadend = ((loadEvent: any) => {
image.src = loadEvent.target.result;
this.croppieImage = myReader.result;
});
image.onload = function(){
// image has been loaded
console.log(image.height);
};
Upvotes: 2
Reputation: 27353
Try This
reader.onload = (event) => {
var img = new Image;
this.url = event.target.result;
img.src = event.target.result;
console.log(img.width);
}
Example:https://stackblitz.com/edit/angular-file-upload-preview-yxuayc
Upvotes: 1