首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不刷新文件标签的情况下获得图像的高度和宽度?

如何在不刷新文件标签的情况下获得图像的高度和宽度?
EN

Stack Overflow用户
提问于 2011-07-09 07:03:10
回答 1查看 5.1K关注 0票数 2

可能重复: 使用javascript获取文件标记中的图像高度和宽度

如何在不刷新文件标签的情况下获得图像的高度和宽度?

代码语言: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代码获得图像的高度和宽度,但是这个时间页将被刷新,如果不刷新页面,我可以得到图像大小,而不是高度和宽度.

EN

回答 1

Stack Overflow用户

发布于 2011-07-09 09:23:56

您可以通过iframe上传文件,并在iframe重新加载后获得图像宽度/高度。在现代浏览器中,您可以使用FileReader API:

代码语言:javascript
复制
<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中读取文件有一个很好的帖子

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6633290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档