3

I receive base64 string of an image and use it as source for in html page. In turn, img is a child of div. I want to get div automatically resized by the image dimensions. Tried to get dimensions of an image using javascript (... = element.style.height), but it didn't work (I think it's because asynchronous loading of an image). Now I think that maybe it is possible to get image dimensions in advance and calculate size of a parent div manually.

Is it somehow possible to extract image dimensions from base64 string without decoding it completely?

EDITED I used onload method to resize the parent div.

Sergey
  • 1,168
  • 2
  • 13
  • 28

1 Answers1

6

That would depend on the image format.

For example, in PNG it's quite simple: decode the first 32 base64 chars in 24 bytes: check that the positions 1-3 consists of ASCII string 'PNG' and then read width and height in positions 16-19 and 20-23 http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html

leonbloy
  • 73,180
  • 20
  • 142
  • 190