2013-03-19 63 views
27

我正在構建圖像調整大小/作物,並且我想在模型(引導程序)中編輯它之後顯示實時預覽。這個應該工作,我相信,但我只是在console.log中得到0。這就需要餵養的寬度和原始圖像的高度到另一個腳本(我將在以後做什麼,只需要他們的console.log /現在一個變量)使用filereader獲取圖像的寬度和高度

function doProfilePictureChangeEdit(e) { 
    var files = document.getElementById('fileupload').files[0]; 
    var reader = new FileReader(); 
    reader.onload = (function(theFile) { 
     document.getElementById('imgresizepreview').src = theFile.target.result; 

     document.getElementById('profilepicturepreview').src = theFile.target.result; 
     } 
    ); 
    reader.readAsDataURL(files); 
    var imagepreview = document.getElementById('imgresizepreview'); 
    console.log(imagepreview.offsetWidth); 
    $('img#imgresizepreview').imgAreaSelect({ 
     handles: true, 
     enable: true, 
     aspectRatio: "1:1", 
     onSelectEnd: preview 
    }); 
    $('#resizeprofilepicturemodal').modal('show'); 
    }; 

回答

70

你要等待圖像加載。嘗試處理.onload中的元素。

我也簡化了設置兩個元素源的過程,以便如何使用它(使用jQuery)。

reader.onload = (function(theFile) { 
    var image = new Image(); 
    image.src = theFile.target.result; 

    image.onload = function() { 
     // access image size here 
     console.log(this.width); 

     $('#imgresizepreview, #profilepicturepreview').attr('src', this.src); 
    }; 
}); 
+0

大的方式,非常感謝。我誤以爲這些文件會加載readAsDataURL調用。 – 2013-03-19 04:34:02

+1

當文件系統完成從硬盤讀取文件時調用'reader.onload'。本質上,圖像對象已經在瀏覽器中緩衝了圖像數據時調用'image.onload'。我看你怎麼會誤解onload函數;很高興有幫助。 – 2013-03-19 05:45:44

+1

注意:這僅適用於使用「reader.readAsDataURL」的情況。用「reader.readAsBinaryString」你必須採取不同的方式。 – 2014-01-30 14:25:05

15

對我來說奧斯汀的解決沒有工作,所以我提出了我的一個工作:

var reader = new FileReader; 

reader.onload = function() { 
    var image = new Image(); 

    image.src = reader.result; 

    image.onload = function() { 
     alert(image.width); 
    }; 

}; 

reader.readAsDataURL(this.files[0]); 

如果您發現作業image.src = reader.result; image.onload有點有線之後發生, 我也這麼認爲。

+0

它沒有連接圖像加載是異步的。如果src是鏈接,則必須將src中的所有數據解碼,如果base64也必須將其加載並解碼爲圖像。所以這很自然:-) – BrightShadow 2016-05-19 08:26:17

+0

@BrightShadow這是正確的答案。 – 2016-07-16 02:26:59

0

這是我對AngularJS

  fileReader.readAsDataUrl($scope.file, $scope).then(function(result) { 
 
       var image = new Image(); 
 
       image.src = result; 
 
       image.onload = function() { 
 
        console.log(this.width); 
 
       }; 
 
       $scope.imageSrc = result; //all I wanted was to find the width and height 
 

 

 
      });

相關問題