Skip to content Skip to sidebar Skip to footer

How To Convert Base64 String To A Pil Image Object

import base64 from PIL import Image def img_to_txt(img): msg = '' msg = msg + '' with open(img, 'rb') as imageFile: msg = msg + str(ba

Solution 1:

PIL's Image.open can accept a string (representing a filename) or a file-like object, and an io.BytesIO can act as a file-like object:

import base64
import io
from PIL import Image

def img_to_txt(filename):
    msg = b"<plain_txt_msg:img>"
    with open(filename, "rb") as imageFile:
        msg = msg + base64.b64encode(imageFile.read())
    msg = msg + b"<!plain_txt_msg>"
    return msg

def decode_img(msg):
    msg = msg[msg.find(b"<plain_txt_msg:img>")+len(b"<plain_txt_msg:img>"):
              msg.find(b"<!plain_txt_msg>")]
    msg = base64.b64decode(msg)
    buf = io.BytesIO(msg)
    img = Image.open(buf)
    return img

filename = 'test.png'
msg = img_to_txt(filename)
img = decode_img(msg)
img.show()

Post a Comment for "How To Convert Base64 String To A Pil Image Object"