2016-12-15 11 views
1

私は画像ファイルをアップロードするコードを書いています。私は、アップロードする関数を呼び出す前に、アップロードされる画像の大きさ(高さと幅)を知る必要があります。角度2の画像サイズを取得

角度2で画像の寸法を抽出する方法はありますか?もしそうなら、どうですか?あなたは次のように画像の高さと幅を見つけるために、JSコードを使用する必要が

+0

あなたはイメージオブジェクトそのものを取得する必要があり、その後、サイズを求めます。コードはどのように見えますか? – John

答えて

-1

:上記のコードで

<!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> 

我々は後に、アップロードプロセスチェックの高さと幅の間に、画像要素で選択した画像を配置する必要があるとアップロードするプロセス。

おかげで... angular2ように

+0

質問が明らかにangular2の場合、どうしてjQueryがここで助けになるのでしょうか? –

2

は、私は、任意の要素の高さと幅を取得するには、カスタムディレクティブを作成します。 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; }

関連する問題