繁体   English   中英

使用 TypeScript 获取 Angular 中图像的高度和宽度

[英]Getting the height and width of an image in Angular using TypeScript

我正在尝试使用其 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。
谢谢!!

您需要查看 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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM