2017-02-18 49 views
0

我想讀取我用HTML輸入元素(類型爲文件)選取的圖像文件的「寬度」和「高度」。我的問題是,當我第一次選擇圖像文件時,我得到的值爲0/0。當我選擇第二個圖像文件(哪一個不重要)時,我會得到第一張/上一張圖像的寬度和高度的正確值。HTML5:輸入類型文件 - 讀取圖像數據

如何確保立即獲取我選擇的圖像文件的寬度和高度?

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <meta charset="utf-8"> 
 
</head> 
 
<body> 
 

 
\t <input type="file" id="fileInput" accept="image/*" onchange="handleFiles(this.files)"> 
 
\t 
 
\t <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> 
 
\t <script> 
 
\t \t var img = new Image(); 
 
\t \t //set input back to default on refresh: 
 
\t \t $('#fileInput')[0].value = ""; 
 
\t \t 
 
\t \t function handleFiles(fileList) { 
 
\t \t \t if (!fileList.length) { 
 
\t \t \t \t console.log("No files selected!"); 
 
\t \t \t } else { 
 
\t \t \t \t console.log(fileList.length); 
 
\t \t \t \t console.log(fileList[0]); 
 
\t \t \t \t 
 
\t \t \t \t img.src = window.URL.createObjectURL(fileList[0]); 
 
\t \t \t \t 
 
\t \t \t \t console.log("src: " + img.src); 
 
\t \t \t \t console.log("width: " + img.width + "/height: " + img.height); 
 
\t \t \t \t 
 
\t \t \t \t img.onload = function() { 
 
\t \t \t \t \t window.URL.revokeObjectURL(this.src); 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t } 
 
\t </script> 
 
</body> 
 
</html>

+0

我打上你的答案是有用的,但得到這個消息:「感謝您的反饋!記錄的聲望低於15的演員的投票記錄,但不改變公開顯示的職位得分。「 – voland

回答

2

你需要得到寬度/高度在onload事件(img.onload = function() {...}

注意,如@guest271314指出,使用naturalWidth/naturalHeight代替width/height

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
</head> 
 

 
<body> 
 

 
    <input type="file" id="fileInput" accept="image/*" onchange="handleFiles(this.files)"> 
 

 
    <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> 
 
    <script> 
 
    var img = new Image(); 
 
    //set input back to default on refresh: 
 
    $('#fileInput')[0].value = ""; 
 

 
    function handleFiles(fileList) { 
 
     if (!fileList.length) { 
 
     console.log("No files selected!"); 
 
     } else { 
 
     console.log(fileList.length); 
 
     console.log(fileList[0]); 
 

 
     img.src = window.URL.createObjectURL(fileList[0]); 
 

 
     console.log("src: " + img.src); 
 

 
     img.onload = function() { 
 
      window.URL.revokeObjectURL(this.src); 
 

 
      console.log("width: " + img.naturalWidth + "/height: " + img.naturalHeight); 
 

 
     } 
 
     } 
 
    } 
 
    </script> 
 
</body> 
 

 
</html>

相關問題