可能重复:
get image height and width in file tag using javascript
如何在文件标签中没有页面刷新的情况下获得图像的高度和宽度?
<HTML>
<HEAD>
<TITLE></TITLE>
<script language="javascript">
function getW(){
var theImg = document.getElementById('testimg');
alert(theImg.width);
}
function getH(){
var theImg = document.getElementById('testimg');
alert(theImg.height);
}
</script>
</HEAD>
<BODY>
<input type="file" id="testimg"/>
<input type="button" value="get Width" onclick="getW()"/>
<input type="button" value="get Height" onclick="getH()"/>
</BODY>
</HTML>
我使用php代码获取图像的图像高度和宽度,但该时间页面将刷新,没有页面刷新我得到图像大小但不是高度和宽度....
答案 0 :(得分:3)
您可以通过iframe上传文件,然后重新加载iframe获取图片宽度/高度。在现代浏览器中,您可以使用FileReader API:
<input type="file" id="files" multiple/>
<script type="text/javascript">
function handleFileSelect() {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', theFile.name, '"/>'].join('');
document.body.appendChild(span);
var img = span.getElementsById('img');
img.onload = function() {
alert(img.src, img.offsetWidth, img.offsetHeight);
document.body.removeChild(span);
}
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
javascript中有一个很好的post阅读文件。