【问题标题】:Getting the height and width of an image in Angular using TypeScript使用 TypeScript 在 Angular 中获取图像的高度和宽度
【发布时间】:2021-11-17 13:39:11
【问题描述】:

我正在尝试使用图像的 src URL 获取图像的宽度和高度。
此代码将“undefinedxundefined”输出到控制台。
这就是我现在拥有的:

  getImageSize(image: string) {
let width;
let height;
let img = new Image();
img.src = image;
img.onload = function (event) {
  let targetImg = event.currentTarget as HTMLImageElement;
  width = targetImg.width;
  height = targetImg.height
}
return width + "x" + height;

}

我使用的是 Angular 12.2.11 版。
谢谢!!

【问题讨论】:

    标签: javascript angular typescript angular-cli angular12


    【解决方案1】:

    您需要查看 Observable 和订阅:

    getImageSize(url: string): Observable<any> {
      return new Observable(observer => {
        var image = new Image();
        image.src = url;
    
        image.onload = (e: any) => {
          var height = e.path[0].height;
          var width = e.path[0].width;
    
          observer.next(width + 'x' + height);
          observer.complete();
        };
      });
    }
    

    然后您可以订阅该 observable 并从中获取响应:

    this.getImageSize('your image url').subscribe(response => {
      console.log(response);
    });
    

    这将返回width + 'x' + height

    【讨论】:

      【解决方案2】:

      要获取任何 HTML 元素的矩形,请使用:

      const el = document.getElementById('dd');
      const rect = el.getBoundingClientRect();
      const height = rect.height;
      const width = rect.width;
      

      【讨论】:

        猜你喜欢
        • 2010-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-04
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多