2016-12-15 35 views
1

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

有没有方法可以提取图像尺寸的角度2?如果是这样,怎么样?

+0

你必须获得图像对象本身,然后索要大小。你的代码是怎样的? – John

回答

-1

你必须使用JS代码,以查找高度和图像的宽度如下:

<!DOCTYPE html> 
<head> 
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
<script> 
function readURL(input) 
{ 
    if (input.files && input.files[0]) { 
     var reader = new FileReader(); 

     reader.onload = function (e) { 
      $('#image1') 
      .attr('src', e.target.result);    
     }; 

     reader.readAsDataURL(input.files[0]); 
    } 
} 

function upload() 
{ 
    var img = document.getElementById('image1'); 
    var width = img.clientWidth; 
    var height = img.clientHeight; 
    alert(width + " : " + height); 

    //check height and width using above two variables (width/height) in if block and place upload code in if block... 
} 
</script> 
</head> 
<body> 
<input type='file' onchange="readURL(this);" /><input type="button" value="Upload" onClick="upload()" /><br> 
<img id="image1" src="#" alt="your image" height="auto" width="auto" /> 
</body> 
</html> 

在我们必须把所选图像中的图像元素上面的代码,在上传过程检查高度和宽度,后过程上传。

谢谢...

+0

我无法想象为什么如果问题显然是关于angular2的,jQuery如何在这里帮助? –

2

在angular2方式,我将创建一个自定义的指令来获得任何元素的高度和宽度。对于img,我会在img标记中应用它(指示),并且每当我想要获得高度& img的宽度时,我只需要点击它即可。你可以根据你的需要进行修改。

DEMO:https://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview

directive.ts

import { Directive,Input,Outpu,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); 
    } 
} 

app.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'; 
} 
0

我创建函数获取图像尺寸

getImgSize(image: string): Observable<ISize> { 
    let mapLoadedImage = (event): ISize => { 
     return { 
      width: event.target.width, 
      height: event.target.height 
     }; 
    } 
    var image = new Image(); 
    let $loadedImg = Observable.fromEvent(image, "load").take(1).map(mapLoadedImage); 
    image.src = image; 
    return $loadedImg; 
} 

interface ISize { width: number; height: number; }