1

I'd like to read "width" and "heigth" of an image file that I pick with HTML input element (type is file). My problem is, that I get the values 0 / 0 when I pick an image file for the first time. When I pick a second image file (doesn't matter which one), I get the correct values for width and height for the first/previous image.

How can I make sure to instantly get width and heigth of the image file I picked?

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

1
  • I marked your answer useful, but get this message:"Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score."
    – voland
    Commented Mar 5, 2017 at 17:32

1 Answer 1

3

You need to get width/height in the onload event (img.onload = function() {...})

Note, as @guest271314 pointed out, use naturalWidth/naturalHeight instead of 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>

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.