2

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

Community
  • 1
  • 1
srbhbarot
  • 1,317
  • 12
  • 16

1 Answers1

3

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.

anton_byrna
  • 2,477
  • 1
  • 18
  • 31