如何将 base64 字符串转换为 PIL Image 对象 [英] How to convert base64 string to a PIL Image object

查看:35
本文介绍了如何将 base64 字符串转换为 PIL Image 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 模块一起使用.

How do I convert the string to a PIL Image object, I was thinking of using the function frombytes() withing the Image module from PIL.

推荐答案

PIL 的 Image.open 可以接受字符串(表示文件名)或类似文件的对象,并且io.BytesIO 可以行动作为类文件对象:

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

这篇关于如何将 base64 字符串转换为 PIL Image 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆