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>