Search code examples
pythonbase64jpeg

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?


Solution

  • 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