0
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图像对象,我正在考虑使用来自Piles的Image模块的Bytes()函数。如何将base64字符串转换为PIL图像对象

回答

2

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() 
相关问题