我正在尝试在HTML5中调整图片大小,有很多关于如何做到这一点的例子,但是无法通过这一点。这是代码片段,对我不起作用。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Picture Test</title>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<form action="/MyWebsiteLogo/LogoPicture/95" enctype="multipart/form-data" id="picture" method="post">
<div style="width: 100%; padding: 0px;">
<input id="input" name="file" onchange="handleFiles()" type="file" value="" /><br /><br />
<input type="submit" value="Upload" />
</div>
<script>
function handleFiles() {
var fileList = input.files;
var file = fileList[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function (e) { img.src = e.target.result }
reader.readAsDataURL(file);
var width = img.width;
var height = img.height;
}
</script>
</form>
</body>
</html>
当我运行此代码并选择文件时,Google调试器显示该文件已被选中,但img和reader未使用所选文件进行初始化(请参阅下面的两个屏幕截图)。我究竟做错了什么?谢谢!
答案 0 :(得分:2)
当您尝试获取img.width
和img.height
时,img
的src尚未设置。
您必须在img
的{{1}}事件处理程序中设置这些变量。
onload
function handleFiles() {
var fileList = input.files;
var file = fileList[0];
var img = document.createElement("img");
img.onload = function(){
var width = img.width;
var height = img.height;
snippet.log('width: '+ width);
snippet.log('height: '+height);
}
var reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
}
reader.readAsDataURL(file);
}
答案 1 :(得分:1)
在此代码中,您现在可以看到预览图像。但是你想调整大小图像。 resize
什么?
function handleFiles() {
var fileList = input.files;
var file = fileList[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function (e) {
img.onload = function() {
// This width and height will be correct because until now the image are not get the src
var width = img.width;
var height = img.height;
alert(width + ',' + height);
}
img.src = e.target.result;
}
reader.readAsDataURL(file);
var width = img.width;
var height = img.height;
document.body.appendChild(img);
}
&#13;
<form action="/MyWebsiteLogo/LogoPicture/95" enctype="multipart/form-data" id="picture" method="post">
<div style="width: 100%; padding: 0px;">
<input id="input" name="file" onchange="handleFiles()" type="file" value="" /><br />
<br />
<input type="submit" value="Upload" />
</div>
</form>
&#13;