Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Base64 image dimension in python

Assuming one has a base64 encoded image.

How can one extract the image dimensions from the string, preferably without storing the string to disc as an image?

For PNG files, I can get this from bytes 16-24 of the string which are part of the PNG header, but for JPEG images, it appears no such hack exists.

What are some nice ways of getting the image dimensions in this case?

like image 233
nbubis Avatar asked Dec 11 '17 15:12

nbubis


People also ask

How is Base64 image size calculated?

Base64 encodes 3 bytes of binary data on 4 characters. So to get the size of the original data, you juste have to multiply the stringLength (minus the header) by 3/4.


1 Answers

Using the pillow library one can do:

import io
import PIL
from PIL import Image

imgdata = base64.b64decode(base64_str)
im = Image.open(io.BytesIO(imgdata))
width, height = im.size
like image 100
nbubis Avatar answered Nov 07 '22 12:11

nbubis