Getting Image Dimensions using Javascript File API

Abishek picture Abishek · Sep 18, 2011 · Viewed 66.3k times · Source

I require to generate a thumbnail of an image in my Web Application. I make use of the Html 5 File API to generate the thumbnail.

I made use of the examples from the below URL to generate the thumbnails.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

I am successfully able to generate the thumbnails. The problem that I have is I am able to generate thumbnail only by using a static size. Is there a way to get the file dimensions from the selected file and then create the Image object?

Answer

pimvdb picture pimvdb · Sep 18, 2011

Yes, read the file as a data URL and pass that data URL to the src of an Image: http://jsfiddle.net/pimvdb/eD2Ez/2/.

var fr = new FileReader;

fr.onload = function() { // file is loaded
    var img = new Image;

    img.onload = function() {
        alert(img.width); // image is loaded; sizes are available
    };

    img.src = fr.result; // is the data URL because called with readAsDataURL
};

fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating