Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert base64 string to a PIL Image object

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

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.

like image 733
Joseph Long Avatar asked Jul 15 '17 21:07

Joseph Long


People also ask

How do I decrypt a Base64 string?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.


1 Answers

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()
like image 199
unutbu Avatar answered Oct 20 '22 06:10

unutbu