0

just messing about trying to learn it. Im trying to validate an image from an upload. Checking the image type works fine with the code below. but im trying to check its size. Can anyone explain why this is not working please.

Thanks.

  $('#File').change(function (evt) {
            var f = evt.target.files[0];
            var reader = new FileReader();


            var H = f.height;
            var W = f.width;

            if (W > 100) {
                alert("The selected file is too large.");
                return;
            }


            if (!f.type.match('image.*')) {
                alert("The selected file does not appear to be an image.");
                return;
            }

            setBox('#IsFile');
            reader.onload = function (e) { preview.attr('src', e.target.result); };
            reader.readAsDataURL(f);
        });
loveforfire33
  • 1,090
  • 3
  • 25
  • 46
  • It's not working because the API provides no support for it. The "height" and "width" properties will always be `undefined`, in other words. (At least, that's true in my browser.) – Pointy Nov 21 '13 at 17:16
  • thanks for your reply. So is it not possible to check the image size in jquery? – loveforfire33 Nov 21 '13 at 17:19
  • Well you could do it, but you'd have to read the file contents and then decode the image format enough to extract that information with your own code. – Pointy Nov 21 '13 at 17:19
  • I suppose you could load it into a hidden element and do something like this: http://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript – Robb Nov 21 '13 at 17:19
  • Yes, that would be a lot easier than my dumb idea :) – Pointy Nov 21 '13 at 17:20
  • @Robb not hidden...offscreen though will work – charlietfl Nov 21 '13 at 17:31
  • @charlietfl err right. Hidden wouldn't work would it. Thanks! – Robb Nov 21 '13 at 17:32

1 Answers1

0

A workaround would be to load the image into an offscreen image element and then detect the Width/Height using a method similar to this:

var img = document.getElementById('offscreenImageId'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
Robb
  • 2,666
  • 4
  • 20
  • 24