以角度 2 获取图像尺寸

新手上路,请多包涵

我正在编写代码来上传图像文件。在调用上传函数之前,我需要知道将要上传的图像的尺寸(高度和宽度)。

有没有一种方法可以在角度 2 中提取图像尺寸?如果是这样,如何?

原文由 SoundStage 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 382
2 个回答

我创建了获取图像大小的函数

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; } 您也可以在 html 中订阅加载事件 <img (load)="loadedImg($event)" [src]="imageSrc"> 并从中获取大小。

原文由 kostia24 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题