我想读取我使用 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>
最佳答案
您需要在 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>
关于javascript - HTML5 : Input Type File - read image data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42318829/