开发者

how can i get the height and width of image without page refresh in file tag? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

get image height and width in file tag using javascript

how can i get the height and width of image without page refresh in file tag?

<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>

i get the image height and width of image using php code, but that time page will be refreshed, without page refresh i get image size but not a height and width....


You can upload file through iframe and after iframe reloaded get image width/height. In modern browsers you can use 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>

There is an excellent post about reading file in javascript.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜