ccdavies
ccdavies

Reputation: 1606

Getting file width and height with File API

I haven't used HTML5 File API much, so am pretty new to it.

I am trying to get the width and height of a file from the file upload field '#submission-file' field into two variables.

Here is the code I have:

    var fileWidth = 0;
    var fileHeight = 0;
    var url = window.URL || window.webkitURL;
    var fileField = $('#submission-file')[0].files[0];
    var image = new Image();
    image.onload = function() {
        fileWidth = $('#submission-file').width;
        fileHeight = $('#submission-file').height;
    };
    image.src = url.createObjectURL(fileField); 

Can anyone show me what I am doing wrong?

Upvotes: 0

Views: 5570

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

You could use this snippet, give you the idea:

http://jsfiddle.net/Mqvgx/

function getImgSize(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#testImg').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$('#testImg').on('load', function () {
    alert($(this).width() + '*' + $(this).height());
})

$("input").change(function () {
    getImgSize(this);
});

Upvotes: 4

Related Questions