18

How can I find the Base64 image width and height?

<img id="thumb0" width="200" height="200"
src="data:image/png;base64, ................">

The image properties width and height are constant as I need to show them as a thumbnail, but whereas the original image properties are different.

I need to get the original image height and width.

Suppose my original image height and width are 750 X 500 pixels.

I tried like this, but I am getting the property width and height:

$("#thumb0").width();

The value is 200.

How can I get the original width and height of the image?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vvr02
  • 611
  • 2
  • 12
  • 22
  • 1
    Images (on Firefox at least) have a naturalWidth/height property so you can use img.naturalWidth to get the original width – Sai Prasad Jan 11 '13 at 09:18
  • tried in firebug in firefox it is saying undefined – vvr02 Jan 11 '13 at 09:23
  • 1
    Its working for me in both Firefox and Chrome.. Note that the image must be completely loaded to use naturalWidth / naturalHeight properties.. – Sai Prasad Jan 11 '13 at 09:27
  • @SaiPrasad +1 This is a good idea but I can't find information regarding compatibility of this property which was, I think, only normalized in HTML5. If you can find it, this should be an answer. – Denys Séguret Jan 11 '13 at 09:31
  • You can find answer in another question, here: http://stackoverflow.com/questions/17774928/js-get-image-width-and-height-from-the-base64-code – MichaelLuthor Nov 22 '13 at 06:38

2 Answers2

18

You can build another image element and get its size:

var img = new Image();
img.src = $('#thumb0').attr('src');
var originalWidth = img.width;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 3
    But i think it will take to time for huge images and we need to destroy after creating? – vvr02 Jan 11 '13 at 09:25
  • 1
    No, it will be very fast, especially as there is no request to issue. And you have no destruction to do : as soon as you leave the function where img is declared, it's cleaned. – Denys Séguret Jan 11 '13 at 09:29
  • @dystroy It does not work in android ~~~, any way to make it works ? – MichaelLuthor Nov 22 '13 at 06:34
14

The Image() constructor for HTMLImageElements mentioned in Denys Séguret's answer is the right way to go, but there's a caveat: The constructor is actually asynchronous! As a result, you may experience unexpected behavior in certain browsers; from my limited experiments, Denys Séguret's code will work 100% of the time in Chrome, but only sometimes in Firefox and Safari. Don't know about others.

The right way to do it seems to be with an onload handler, as in:

var img = new Image();
img.src = some_base64_image_source;
console.log(img.width);       // This might print out 0!
img.onload = function() {
    console.log(img.width);   // This will print out the width.
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ycz6
  • 141
  • 1
  • 5