Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image dimensions from base64 string

Tags:

image

base64

png

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.

like image 637
Sergey Avatar asked Jun 10 '26 04:06

Sergey


1 Answers

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

like image 98
leonbloy Avatar answered Jun 11 '26 21:06

leonbloy



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!