FileReader API - Getting image width

Hi,

I have an image upload form with image preview. When a user selects an image from their desktop, the image is displayed in the preview before upload. I want to get the width of that image if possible but I don’t know how to get it. I have the following code:

function readURL(input) {
	if (input.files && input.files[0]) {
		var reader = new FileReader();
		reader.onload = function (e) {
			$('#preview').attr('src', e.target.result).css('width', ???);
		};
		reader.readAsDataURL(input.files[0]);
		}
	}
}

I have ??? in where I want to get the selected image width. Do you have any ideas how to do that?

Thanks.

Hi nayen,

You can do it like this:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Get image width using File API</title>
  </head>

  <body>
    <input type='file' onchange="readURL(this);" />

    <script>
      function readURL(input) {
        if (input.files && input.files[0]) {
          var reader = new FileReader();
          reader.onload = function (e) {
            var img = new Image;
            img.onload = function() {
              console.log("The width of the image is " + img.width + "px.");
            };
            img.src = reader.result;
          };
          reader.readAsDataURL(input.files[0]);
        }
      }
    </script>
  </body>
</html>

Basically you create a new image, set its src attribute to what is returned by reader.result, then use the image’s onload method to access its properties.

Hope that helps.

BTW, this article about the File API appeared on JSPro this week. It might be worth a read.

Thank you very much Pullo. I took one bit from your code and adapted to mine and here is what I came up with that works just as I wanted:

function readURL(input) {
	if (input.files && input.files[0]) {
		var reader = new FileReader();
		reader.onload = function (e) {
			var img = new Image;
			img.onload = function() {
				$('#preview').attr('src', e.target.result).css('max-width', img.width+'px');
			};
			img.src = reader.result;
		};
		reader.readAsDataURL(input.files[0]);
		}
	}
}

Do you think I have obsolete code in the jQuery line?

No, that looks fine to me.

I was wondering why you had:

if (input.files && input.files[0]) {
   ...
}

but I guess that’s to weed out browsers that don’t support the File API.

I don’t know. It is part of a code I found somewhere else.

I’m pretty sure that’s what it’s for.
I just tried your script out on IE7 and it dies with the following error:

Die Eigenschaft "0" eines undefinierten oder Nullverweises kann nicht abgerufen werden.

Which refers to the check if input.files[0] evaluates to true.