2017-02-18 45 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>

相关问题