【问题标题】:How can i catch the width and height of a image link in angular?如何以角度捕捉图像链接的宽度和高度?
【发布时间】:2019-06-06 16:33:07
【问题描述】:

我需要验证图片的链接是否为 1000px x 1000px 和 jpg。

示例:

https://www.w3schools.com/bootstrap/paris.jpg

我有这个链接,我需要捕捉这张图片的宽度和高度。

我认为 jpg 问题很容易解决,我会在最后几个字符中给出一个子字符串,但是图像大小的问题我不知道如何在 angular 中找到。

有人有什么想法吗?谢谢。

【问题讨论】:

  • 我需要打字稿
  • 和javascript有点不同
  • 只要将 typescript 转译成 javascript,每个 javascript 代码都是有效的 Typescript(解释如下:stackoverflow.com/questions/20759532/…)。
  • 我试试:@ViewChild('imgprincipal') imgprincipal 我的img:image.flaticon.com/icons/svg/190/190406.svg '" src="{{produto.foto_prin_1}}" height="50" width="50"> 当我尝试 (console.log(this.imgprincipal.nativeElement.offsetWidth) 我收到:“无法读取属性 'nativeElement '未定义的

标签: angular typescript


【解决方案1】:

创建一个指令并使用它,如下所示:

import { Directive,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[imgDimension]",
  host:{
    '(click)':"calculate()"
  }
})

export class GetImageDmnsn{ 

  constructor(private img:ElementRef){

  }
  calculate(){
    console.log('height:' + this.img.nativeElement.offsetHeight);
    console.log('width:' + this.img.nativeElement.offsetWidth);   
  }
}
<img imgDimension [src]="source">  

【讨论】:

  • 当我尝试将链接放入 img 时,我收到的类型“字符串”不可分配给类型“ElementRef”。
【解决方案2】:

这里是javascript方式:

function getImageDimenstion(imgUrl){

   let img = new Image(); 

   img.src = imgUrl;
   img.onload = function (event) {
        let  loadedImage = event.currentTarget;
        let width = loadedImage.width;
        let height = loadedImage.height;
        console.log('height: '+height);
        console.log('width: '+width);
   } 
}

const url= "https://www.w3schools.com/bootstrap/paris.jpg";
getImageDimenstion(url);

角度的工作示例:

Working Demo

【讨论】:

  • 我怎样才能在打字稿变量中捕捉到这个宽度/高度?
  • 如果我尝试 this.width = width 我收到:“[ts] 属性 'width' 在类型 'HTMLElement' 上不存在。
  • 迟到但打字稿会同意这一点:let loadedImage = event.currentTarget as HTMLImageElement;。然后,您可以访问所有HTMLImageElement properties,如loadedImage.width
【解决方案3】:

我想分享我对这个问题的解决方案,因为我无法访问其他解决方案中给出的回调函数之外的图像高度和宽度。这是对我有用的解决方案:

let img = new Image();
img.src = "https://yourImageSource";

现在,如果您想使用图像高度/宽度,只需使用img.naturalHeightimg.naturalWidth

注意:在我的 Angular 项目中的现代浏览器中工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 2019-06-19
    相关资源
    最近更新 更多