简体   繁体   English

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

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

I'm trying to get the width and height of an image using its src URL.我正在尝试使用其 src URL 获取图像的宽度和高度。
This code outputs "undefinedxundefined" to the console.此代码将“undefinedxundefined”输出到控制台。
This is what I have now:这就是我现在所拥有的:

  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;

} }

I'm using Angular version 12.2.11.我正在使用 Angular 版本 12.2.11。
Thanks!!谢谢!!

You need to look into Observable and subscriptions:您需要查看 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();
    };
  });
}

Then you can subscribe to that observable and get the response from it:然后,您可以订阅该 observable 并从中获取响应:

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

and that will return the width + 'x' + height .这将返回width + 'x' + height

To get the rect of any HTML element use:要获得任何 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