Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width and height of an image loaded via a FileReader [duplicate]

I have an image that is created via a FileReader:

    var fileReader = new FileReader();
    var deferred = $.Deferred();

    fileReader.onload = function(event) {
        deferred.resolve(event.target.result);
    };

    fileReader.onerror = function() {
        deferred.reject(this);
    };

    fileReader.readAsDataURL(file);

    return deferred.promise();

This returns a base64 encoded string which I use with:

var img = $('<img src="' + fileB64 + '">');

Then this is added to my page.

I wish to get the original height and width of that image.

I can get the size of it on the page via:

this.img = img;
this.imgWidth = this.img.width();
this.imgHeight = this.img.height();

But I wish to get its original width and height.

like image 798
user3729576 Avatar asked Jan 26 '26 10:01

user3729576


1 Answers

I think the only way you can determine the image's width and height is to actually create an image element and then get the dimensions from that:

var img = new Image();
img.src = fileB64;
var width = img.width;
var height = img.height;

I'm assuming (i.e. I haven't checked) that loading a data: URL into an image's src property will cause it to load synchronously. Use img.onload otherwise.

Having created the element off-screen like this, you can then add the very same element into the page.

like image 127
Alnitak Avatar answered Jan 27 '26 23:01

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!