getting image width and height during upload javascript

Viewed 37

Im having trouble obtaining the width and height of an image during the upload function.

Here's the current code I have:

// internal function that creates an input element
var file=newElement("input",0,"");

// sets the input element as type file
file.type="file";
file.multiple="multiple";
file.name="photoupload[]";
file.accept="image/*";

file.onchange=function(e){
  // internal function that creates an image element
  var img=newElement("img",0,"");
  img.src=URL.createObjectURL(this);
  img.onload=function(){
   var cw=img.clientWidth;
   var ch=img.clientHeight;
   alert(cw);alert(ch);
  }
}
file.click();

Not quite sure how to fix this. Any help appreciated.

1 Answers

Swap the onload to before the change of src and use width and height.

The onload needs to exist before the src is changed

I assume newElement is a function that does a document.createElement - if it does not return an image object, you need to move the onload to that function

// internal function that creates an input element
var file=newElement("input",0,"");

// sets the input element as type file
file.type="file";
file.multiple="multiple";
file.name="photoupload[]";
file.accept="image/*";

file.onchange=function(e){
  // internal function that creates an image element
  var img=newElement("img",0,"");
  img.onload=function(){
   var cw=img.width;
   var ch=img.height;
   console.log(cw,ch);
  }
  img.src=URL.createObjectURL(this);
}
file.click();
Related