HTML5:输入类型文件 - 读取图像数据

时间:2017-02-18 18:08:32

标签: javascript html5 input

我想阅读"宽度"和" heigth"我用HTML输入元素选择的图像文件(类型是文件)。我的问题是,当我第一次选择图像文件时,我得到值0/0。当我选择第二个图像文件(并不重要)时,我得到第一个/上一个图像的宽度和高度的正确值。

如何确保立即获取我选择的图像文件的宽度和高度?



<!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);
				console.log("width: " + img.width + " / height: " + img.height);
				
				img.onload = function() {
					window.URL.revokeObjectURL(this.src);
				}
			}
		}
	</script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您需要在onload事件(img.onload = function() {...}

中获取宽度/高度

请注意,正如@guest271314指出的那样,使用naturalWidth / naturalHeight代替width / height

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;