5

I'm designing a website for a printing company. They want an image size/resolution checker that will let their customers upload an image they want to print, and tell them if the image resolution is good enough for printing.

I'm using Adobe Muse, so I need a simple HTML and CSS solution to this without any server-side requirements.

This is what I have so far, based on this question:

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 { 
                //stop
            } 
        }; 
    } else {
        //No file was input or browser doesn't support client side reading
        form.submit();
    }
});

However, I don't get any popup message. What am I doing wrong?

9
  • So I can't have a simple code that practically says, if the image is smaller than 400x400 display this text or image but if image is or greater than 400x400 display this text or image? Commented Oct 2, 2015 at 17:58
  • Well I found this code that seems to read the dimensions before being uploaded to a server so I assumed it was possible? stackoverflow.com/questions/13572129/… Commented Oct 2, 2015 at 18:10
  • I didn't know that was possible. I stand corrected! Did you have a specific problem getting that code example to work? Commented Oct 2, 2015 at 18:14
  • Well when I added it into muse the pop up with the dimensions didn't appear like it does in the demo... And I really just need to know how to code it so if they upload an image that is or grater than 400 X 400 it says wow you can use this and if it's lower than 400 X 400 it say oops you can't use this. Just don't know how to go about coding this? Commented Oct 2, 2015 at 18:26
  • Can you add the code you've tried so far? Commented Oct 3, 2015 at 16:54

1 Answer 1

7

Your code contains a number of errors, which is why it isn't working. (I don't think the submit event is even being bound to the form, because your jQuery selector doesn't look right: it should be #form or .form)

Here's a working solution:

HTML

<form id="form" action="destination.html">
    <input type="file" id="filePicker" />
    <br/>
    <input type="submit" value="Submit" />
</form>

JS

var _URL = window.URL || window.webkitURL;

function isSupportedBrowser() {
    return window.File && window.FileReader && window.FileList && window.Image;
}

function getSelectedFile() {
    var fileInput = document.getElementById("filePicker");
    var fileIsSelected = fileInput && fileInput.files && fileInput.files[0];
    if (fileIsSelected)
        return fileInput.files[0];
    else
        return false;
}

function isGoodImage(file) {
    var deferred = jQuery.Deferred();
    var image = new Image();

    image.onload = function() {
        // Check if image is bad/invalid
        if (this.width + this.height === 0) {
            this.onerror();
            return;
        }

        // Check the image resolution
        if (this.width >= 400 && this.height >= 400) {
            deferred.resolve(true);
        } else {
            alert("The image resolution is too low.");
            deferred.resolve(false);
        }
    };

    image.onerror = function() {
        alert("Invalid image. Please select an image file.");
        deferred.resolve(false);
    }

    image.src = _URL.createObjectURL(file);

    return deferred.promise();
}


$("#form").submit(function(event) {
    var form = this;

    if (isSupportedBrowser()) {
        event.preventDefault(); //Stop the submit for now

        var file = getSelectedFile();
        if (!file) {
            alert("Please select an image file.");
            return;
        }

        isGoodImage(file).then(function(isGood) {
            if (isGood)
                form.submit();
        });
    }
});

isSupportedBrowser() makes sure that the user's browser supports the required functions before attempting to check the image.

getSelectedFile() makes sure the user has picked a file, and then passes the file data back.

isGoodImage() takes the file data and attempts to construct an image element from it. If onerror is fired, it's not an image or is a corrupted file. If onload is fired, it does a sanity check to make sure the image has valid dimensions, and then validates that the resolution is above 400x400.

Since onerror and onload events are fired asynchronously, the function needs to pass back a promise indicating the result of the validation.

Finally, the submit handler on the form ties all these method calls together and only allows the form to submit if the resolution check comes back good.

Link to fiddle: http://jsfiddle.net/uwj85m7d/7/

Edit As requested, a variant that shows divs containing error messages instead of alert popups: http://jsfiddle.net/uwj85m7d/8/


Further reading:

Sign up to request clarification or add additional context in comments.

20 Comments

That is absolutely fantastic! Just one other question... instead of an "alert" and pop up message, could it be linked it to a web page? or even better have an image appear underneath the submit button?
@GeorgeGibson Sure, that's easy! I added an additional example of showing hidden divs that contain a message. You could easily expand this to include images or styles as you need. If this helped, mind voting up the answer too? :)
In the edited version i added the web page i wanted it to link to if it was correct, for testing purposes google at the moment and then changed the other two to actions and if no file was input but submitted it would go to yahoo and if the wrong file was submitted to go to bing but they all just want to google? am i doing something wrong there too? (sorry for my lack of knowledge, still learning in a way...)
actually when i just add a website destination into the top it then overrides all there other option and stops displaying the text and just goes straight to the destination for everything instead of just a correct image size.....?
@GeorgeGibson I'm confused as to what you are trying to do, sorry. Are you trying to redirect the user depending on the image validation, instead of displaying a message on the form?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.