3

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
user3729576
  • 237
  • 5
  • 10

1 Answers1

2

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • How would I then add the image to the page? I need to get the dimensions later on in another class once it's been added to the page. – user3729576 Jun 11 '14 at 15:02
  • Just use your normal jQuery stuff, e.g. `$(document.body).append(img)` – Alnitak Jun 11 '14 at 15:03
  • But then how do you get the images original width and height? – user3729576 Jun 11 '14 at 15:08
  • if it's already in the page, just read the element's `width` and `height` properties, or are you somehow modifying the element's size before inserting it? If so, the question as asked is a complete red herring. On modern browsers you may be able to use the `naturalWidth` and `naturalHeight` properties, though. – Alnitak Jun 11 '14 at 15:26