我正在编写代码来上传图像文件。在调用上传函数之前,我需要知道将要上传的图像的尺寸(高度和宽度)。
有没有一种方法可以在角度 2 中提取图像尺寸?如果是这样,如何?
原文由 SoundStage 发布,翻译遵循 CC BY-SA 4.0 许可协议
我正在编写代码来上传图像文件。在调用上传函数之前,我需要知道将要上传的图像的尺寸(高度和宽度)。
有没有一种方法可以在角度 2 中提取图像尺寸?如果是这样,如何?
原文由 SoundStage 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 Angular2 方法,我将创建一个自定义指令来获取 任何元素 的高度和宽度。对于 img
,我将在 img
标签中应用它(指令),每当我想获取 img 的高度和宽度时,我只需单击它。您可以根据需要进行修改。
演示: https ://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview
指令.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);
}
}
应用程序.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';
}
原文由 micronyks 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答1.5k 阅读✓ 已解决
2 回答871 阅读✓ 已解决
1 回答1.1k 阅读✓ 已解决
1 回答885 阅读✓ 已解决
2 回答779 阅读
1 回答764 阅读✓ 已解决
2 回答1.1k 阅读
我创建了获取图像大小的函数
interface ISize { width: number; height: number; }
您也可以在 html 中订阅加载事件<img (load)="loadedImg($event)" [src]="imageSrc">
并从中获取大小。