Is it possible to check dimensions of image before uploading?

Sabby62 picture Sabby62 · Nov 26, 2012 · Viewed 78.9k times · Source

I have an upload control for uploading the images to the server, but before uploading I just want to make sure if the images are of correct dimensions. Is there anything on client side that can be done with JavaScript?

Answer

Esailija picture Esailija · Nov 26, 2012

You could check them before submitting form:

window.URL = window.URL || window.webkitURL;

$("form").submit( function( e ) {
    var form = this;
    e.preventDefault(); //Stop the submit for now
                                //Replace with your selector to find the file input in your form
    var fileInput = $(this).find("input[type=file]")[0],
        file = fileInput.files && fileInput.files[0];

    if( file ) {
        var img = new Image();

        img.src = window.URL.createObjectURL( file );

        img.onload = function() {
            var width = img.naturalWidth,
                height = img.naturalHeight;

            window.URL.revokeObjectURL( img.src );

            if( width == 400 && height == 300 ) {
                form.submit();
            }
            else {
                //fail
            }
        };
    }
    else { //No file was input or browser doesn't support client side reading
        form.submit();
    }

});

This only works on modern browsers so you still have to check the dimensions on server side. You also can't trust the client so that's another reason you must check them server side anyway.