Simon Simon - 1 year ago 135
Javascript Question

Check image width and height before upload with Javascript

I have a JPS with a form in which a user can put an image:

<div class="photo">
<div>Photo (max 240x240 and 100 kb):</div>
<input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>

I have written this js:

function checkPhoto(target) {
if(target.files[0].type.indexOf("image") == -1) {
document.getElementById("photoLabel").innerHTML = "File not supported";
return false;
if(target.files[0].size > 102400) {
document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
return false;
document.getElementById("photoLabel").innerHTML = "";
return true;

which works fine to check file type and size. Now I want to check image width and height but I cannot do it.

I have tried with
but I get
. With other ways I get

Any suggestions?

Answer Source

The file is just a file, you need to create an image like so:

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            alert(this.width + " " + this.height);
        img.src = _URL.createObjectURL(file);


I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download