Getting Image Dimensions using Javascript File API

JavascriptThumbnailsFileapi

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Or use an object URL: http://jsfiddle.net/8C4UB/

var url = URL.createObjectURL(this.files[0]);
var img = new Image;
  
img.onload = function() {
    alert(img.width);
    URL.revokeObjectURL(img.src);
};
    
img.src = url;

Solution 3 - Javascript

The existing answers helped me a lot. However, the odd order of events due to the img.onload event made things a little messy for me. So I adjusted the existing solutions and combined them with a promise based approach. Maybe this helps someone else.

Here is a function returning a promise with the dimensions as an object:

const getHeightAndWidthFromDataUrl = dataURL => new Promise(resolve => {
  const img = new Image()
  img.onload = () => {
    resolve({
      height: img.height,
      width: img.width
    })
  }
  img.src = dataURL
})

Here is how you could use it with an async function:

// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]

// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)

// Get dimensions 
const someFunction = async () => {
  const dimensions = await getHeightAndWidthFromDataUrl(fileAsDataURL)
  // Do something with dimensions ...
}

And here is how you could use it using the then() syntax:

// Get a file from an input field
const file = document.querySelector('[type="file"]').files[0]

// Get the data URL of the image as a string
const fileAsDataURL = window.URL.createObjectURL(file)

// Get the dimensions
getHeightAndWidthFromDataUrl(fileAsDataURL).then(dimensions => {
  // Do something with dimensions
})

Solution 4 - Javascript

I have wrapped pimvdb answer in a function for general purpose in my project:

function checkImageSize(image, minW, minH, maxW, maxH, cbOK, cbKO){
    //check whether browser fully supports all File API
    if (window.File && window.FileReader && window.FileList && window.Blob) {
	    var fr = new FileReader;
	    fr.onload = function() { // file is loaded
		    var img = new Image;
		    img.onload = function() { // image is loaded; sizes are available
		    	if(img.width < minW || img.height < minH || img.width > maxW || img.height > maxH){  
				    cbKO();
			    }else{
				    cbOK();
			    }
		    };
		    img.src = fr.result; // is the data URL because called with readAsDataURL
	    };
	    fr.readAsDataURL(image.files[0]);
    }else{
	    alert("Please upgrade your browser, because your current browser lacks some new features we need!");
    }
}    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbishekView Question on Stackoverflow
Solution 1 - JavascriptpimvdbView Answer on Stackoverflow
Solution 2 - JavascriptletmaikView Answer on Stackoverflow
Solution 3 - JavascriptsamView Answer on Stackoverflow
Solution 4 - JavascriptNecrontyrView Answer on Stackoverflow