Getting Image Dimensions using Javascript File API Getting Image Dimensions using Javascript File API javascript javascript

Getting Image Dimensions using Javascript File API


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


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;


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 fieldconst file = document.querySelector('[type="file"]').files[0]// Get the data URL of the image as a stringconst 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 fieldconst file = document.querySelector('[type="file"]').files[0]// Get the data URL of the image as a stringconst fileAsDataURL = window.URL.createObjectURL(file)// Get the dimensionsgetHeightAndWidthFromDataUrl(fileAsDataURL).then(dimensions => {  // Do something with dimensions})