How to convert base64 string to a PIL Image object

后端 未结 1 1854
孤独总比滥情好
孤独总比滥情好 2021-01-12 07:53
import base64
from PIL import Image

def img_to_txt(img):
    msg = \"\"
    msg = msg + \"\"
    with open(img, \"rb\") as imageFile:
              


        
1条回答
  •  臣服心动
    2021-01-12 08:09

    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""
        with open(filename, "rb") as imageFile:
            msg = msg + base64.b64encode(imageFile.read())
        msg = msg + b""
        return msg
    
    def decode_img(msg):
        msg = msg[msg.find(b"")+len(b""):
                  msg.find(b"")]
        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()
    

    0 讨论(0)
提交回复
热议问题