18

How to find the base64 image width and height

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

Image property width and height are constant as i need to show them as thumb nail, but where as 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

I tried like this but getting the property width and height

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

value is 200.

Please help how to get orginal width and height of the image.

vvr02
  • 625
  • 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;
Denys Séguret
  • 355,860
  • 83
  • 755
  • 726
  • 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
  • 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
13

The Image() constructor for HTMLImageElements mentioned in dystroy'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, dystroy'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.
}
ycz6
  • 131
  • 1
  • 5