简体   繁体   中英

HTML5: Input Type File - read image data

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM