1

I was trying to write a function that would check if the image I chose via input[type=file] is exactly 700 px wide and if not - reject this image. I succeeded, however, sometimes this function randomly returns 0 and I need to load the same image a couple of times until it reads its width correctly. Any ideas on how to improve this code? Thanks in advance!

    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var img = new Image;
            img.src = e.target.result;
            if(img.width == 700) {
                DoSomeStuff();
            } else {
                alert("This image has to be 700 px wide, but is " + img.width + " px wide. Try again!");
                input.value = "";
            }
        };
        reader.readAsDataURL(input.files[0]);
    }
Wojciech Maj
  • 982
  • 6
  • 21
  • 1
    http://stackoverflow.com/questions/17774928/js-get-image-width-and-height-from-the-base64-code/17775293#17775293 – gp. Sep 30 '13 at 01:49

1 Answers1

3

Use .onload so the function will only be triggered when the image is loaded.

 if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var img = new Image;


            img.onload = function(){
            if(img.width == 700) {
                DoSomeStuff();
            } else {
                alert("This image has to be 700 px wide, but is " + img.width + " px wide. Try again!");
                input.value = "";
            }
          }


            img.src = e.target.result;
        };
        reader.readAsDataURL(input.files[0]);
    }

Or you can add an event listener:

img.addEventListener("load", function() {
     if(this.width == 700) {
                DoSomeStuff();
            } else {
                alert("This image has to be 700 px wide, but is " + this.width + " px wide. Try again!");
                input.value = "";
     }
}); 

But for ie only ie9 or above support .addEventListener, so for ie8 or below use .attachEvent

img.attachEvent("onload", function() {});

You can do an if-statement to check if browser supports .addEventListener:

if (img.addEventListener)
//return false if broswer does not support
Archy Will He 何魏奇
  • 9,589
  • 4
  • 34
  • 50