0

I have an application that gets an image from the user's local machine. I need to check that the image is <= 2400px in any direction. To do this in the HTML, I've got:

<div style="display:none"><img id="phantom" src=""></div>

The javascript contains the following:

$('#attachment').change(function()
     $('#phantom').attr("src",$('#attachment').val());
     alert($('#phantom').clientWidth+"   "+('#phantom').clientHeight);
});  

All I get in the alert, however is, "undefined undefined".

  • Possible duplicate of [How to Preview Image, get file size, image height and width before upload?](http://stackoverflow.com/questions/12570834/how-to-preview-image-get-file-size-image-height-and-width-before-upload) – Gavriel Feb 07 '16 at 03:09
  • 1
    I don't think setting the src like that will work for a local file, but even if it did, jquery objects don't have clientHeight or clientWidth properties, hence "undefined undefined". – nnnnnn Feb 07 '16 at 03:13

1 Answers1

0
$('<img id="tempimg" src="' + $('#attachment').val() + '" \>).load(function() {
    alert(this.width + "     " + this.height());
});

This will get true width and height for an image, not the client width and client height for the img tag. Note, however, that pulling files from the user's local machine might be against the browser's sandbox environment abilities. You may need to read http://www.dotnetcurry.com/html5/1167/read-local-file-api-html5-javascript to understand HTML5 (assuming that's what you're using) and how to use the window.File API.

Dexter
  • 795
  • 2
  • 13
  • 27
  • Within your load callback `this` will be the img element, so `this.height()` won't work. (Need to lose the parentheses.) – nnnnnn Feb 07 '16 at 03:56
  • yes, you're right. I meant to change that part of it when pasting it in, and forgot. Fixed, thanks. It might also be worth noting that CSS would throw the images width and height off, so I originally meant to use an image tag that was created but not appended. If you needed to load a preview of the image, you could then use the same source to load the '#attachment' image tag. – Dexter Feb 07 '16 at 04:02