I am writing code to upload an image file. I need to know the dimensions(height and width) of the image that will be uploaded before I call the function to upload.
Is there a way in angular 2 by which I can extract the image dimension? If so, how?
I created function to get image size
getImgSize(imageSrc: string): Observable<ISize> {
let mapLoadedImage = (event): ISize => {
return {
width: event.target.width,
height: event.target.height
};
}
var image = new Image();
let $loadedImg = fromEvent(image, "load").pipe(take(1), map(mapLoadedImage));
// Rxjs 4 - let $loadedImg = Observable.fromEvent(image, "load").take(1).map(mapLoadedImage);
image.src = imageSrc;
return $loadedImg;
}
interface ISize { width: number; height: number; }
Also you can subscribe on load event in html
<img (load)="loadedImg($event)" [src]="imageSrc">
and get size from it.
With the Angular2 approach, I'll create a custom directive to get the height and width of any element. For img
, I'll apply it(directive) in the img
tag and whenever I want to get the height & width of an img, I just need click it. You can modify according to your need.
DEMO : https://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview
directive.ts
import { Directive,Input,Output,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[getHeightWidth]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight);
console.log('width---' + this.el.nativeElement.offsetWidth);
}
}
app.ts
@Component({
selector: 'my-app',
template: `
<div style="width:200px;height:300px">
<img getHeightWidth <!-- here I'm using getHeightWidth directive-->
[src]="source" alt="Angular2"
width="100%"
height="100%">
</div>
`,
})
export class AppComponent {
source='images/angular.png';
}
Simply you can use following code to get the width and height (Resolution) of the Image.
HTML Code
<img #pic [src]="imgURL" (load)="onLoad()>
In Angular
@ViewChild('pic', { static: false }) pic: ElementRef;
onLoad() {
console.log((this.pic.nativeElement as HTMLImageElement).naturalWidth);
console.log((this.pic.nativeElement as HTMLImageElement).naturalHeight);
}
In case if you need to get the image size in ts file:
getImageDimension(image): Observable<any> {
return new Observable(observer => {
const img = new Image();
img.onload = function (event) {
const loadedImage: any = event.currentTarget;
image.width = loadedImage.width;
image.height = loadedImage.height;
observer.next(image);
observer.complete();
}
img.src = image.url;
});
}
Call above method:
const image = {
url: 'https://kalgudi.com/store/assets/images/e-mahila1.jpg',
context: 'Mahila self help group'
}
this.getImageDimension(image).subscribe(
response => {
console.log(response);
}
);
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