Search code examples
javascriptthumbnailsfileapi

Getting image dimensions using the JavaScript File API


I require to generate a thumbnail of an image in my web application. I make use of the HTML5 File API to generate the thumbnail.

I made use of the examples from Read files in JavaScript to generate the thumbnails.

I am successfully able to generate the thumbnails, but 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?


Solution

  • 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