【问题标题】:How to convert base64 string to a PIL Image object如何将 base64 字符串转换为 PIL Image 对象
【发布时间】:2017-12-20 17:41:17
【问题描述】:
import base64
from PIL import Image

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

    return msg

class decode:
    def decode_img(msg):
        img = msg[msg.find(
        "<plain_txt_msg:img>"):msg.find(<!plain_txt_msg>")]
        #how do I convert the str 'img', encoded in base64, to a PIL Image?

while 1:
    decode.decode_img(img_to_txt(input()))

如何将字符串转换为 PIL Image 对象,我正在考虑将函数 frombytes() 与 PIL 的 Image 模块一起使用。

【问题讨论】:

    标签: python-3.x character-encoding base64 python-imaging-library


    【解决方案1】:

    PIL's Image.open 可以接受字符串(表示文件名)或类似文件的对象,并且 io.BytesIO 可以充当类似文件的对象:

    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()
    

    【讨论】:

    • msg = msg[msg.find(b"&lt;plain_txt_msg:img&gt;")+len(b"&lt;plain_txt_msg:img&gt;"):TypeError: must be str, not bytes
    猜你喜欢
    • 2015-10-27
    • 2018-04-10
    • 2019-09-22
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2017-06-29
    相关资源
    最近更新 更多