Search code examples
pythonbase64png

Get an image from string Python


I use a google API and now I want to get viewable png image from string, gained from API result.

screenshot": {
  "data": "iVBORw0KGgoAAAANSU...VERY_LONG_STRING",
  "mimeType": "image/png"
 }

I have seen that I should use base64 lib, but It needs byte object, instead of string. Finally I want to view that image manually, so I need to store it to disk.

How should I convert and save it?


Solution

  • base64.b64decode works fine with both strings and bytes:

    In [15]: import base64
    
    In [16]: base64.b64decode('iVBORw0KGgoA')
    Out[16]: b'\x89PNG\r\n\x1a\n\x00'
    
    In [17]: base64.b64decode(b'iVBORw0KGgoA')
    Out[17]: b'\x89PNG\r\n\x1a\n\x00'
    

    Just write it to a file and view the image.