以角度2获取图像尺寸 [英] Get image dimension in angular 2
问题描述
我正在编写代码来上传图片文件。在调用要上传的函数之前,我需要知道将上传的图像的尺寸(高度和宽度)。
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.
在角度2中有没有办法通过我可以提取图像尺寸?如果是这样,怎么做?
Is there a way in angular 2 by which I can extract the image dimension? If so, how?
推荐答案
以angular2方式,我将创建一个自定义指令来获取任何元素。对于 img
,我会在 img
标签中应用它(指令),每当我想获得高度和高度时一个img的宽度,我只需要点击它。您可以根据需要进行修改。
In angular2 way, 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 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
DEMO : https://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview
directive.ts
import { Directive,Input,Outpu,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';
}
这篇关于以角度2获取图像尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!