Ejemplo n.º 1
0
def base64_tools(run):
    """ Some examples of how to use base64 and Pillow """

    if run == True:

        # Binary encode image:
        ico_b = b'R0lGODlhMAAwAHAAACH5BAEAAAEALAAAAAAwADAAgQAAAAAAAAAAAAAAAAK6jI+py+0Po5y0Wgny\n3Sh7wG2fF1ojWU4nmkKr1' \
                b'rpvLK/084JpDuch/zH4REDU0FQ0zpDJ3hIWaSptgWCtKXyOcFTrYbhc\nhFlZanmrMJc7YTb6e0pDwfK3Gq4D6xK2O/yMRuYGxJ' \
                b'CnBcUX54cXVyXIyLKo9+j4BohY2WgJiXnp\n1OXF2cnp+dnZJjalKcgTZbhYGuoKKjXqMCnFtJqrG8jb61VUcnSTCltcityAqjx' \
                b'I2XwJffssXW19\nLV0AADs=\n'

        # String encode image:
        ico_s = """R0lGODlhMAAwAHAAACH5BAEAAAEALAAAAAAwADAAgQAAAAAAAAAAAAAAAAK6jI+py+0Po5y0Wgny3Sh7wG2fF1ojWU4nmkKr1rpvL
        K/084JpDuch/zH4REDU0FQ0zpDJ3hIWaSptgWCtKXyOcFTrYbhchFlZanmrMJc7YTb6e0pDwfK3Gq4D6xK2O/yMRuYGxJCnBcUX54cXVyXIyLKo9
        +j4BohY2WgJiXnp1OXF2cnp+dnZJjalKcgTZbhYGuoKKjXqMCnFtJqrG8jb61VUcnSTCltcityAqjxI2XwJffssXW19LV0AADs="""

        # Tool 1 - Convert binary encode into string encode:
        image_s = ico_b.decode('utf-8')

        # Tool 2 - Create image file from string:
        image_result = open('test_file.png', 'wb')  # create file
        image_result.write(
            base64.decodebytes(ico_b))  # write file for binary encode
        image_result.write(base64.decodebytes(
            ico_s.encode()))  # write file for string encode

        # Tool 3 - Show an image view:
        pic_bytes = base64.b64decode(ico_b)  # trasform into bytes with Base64
        pillow_img = ImageTk.BytesIO(pic_bytes)  # create a pillow image
        img = Image.open(pillow_img)  # get the image with PIL Image
        img.show()  # open-view the image
Ejemplo n.º 2
0
root.title("Encoded Images")
root.geometry("260x50+605+160")  # window size and position

# Config and set icon:
tempfile = '$$_temp.ico'
icondata = b64decode(ico_s)

iconfile = open(tempfile, 'wb')  # create the file
iconfile.write(icondata)  # create the icon
iconfile.close()
icon = PhotoImage(file=tempfile)
root.tk.call('wm', 'iconphoto', root, icon)
remove(tempfile)  # delete the tempfile

# Config Image:
""" From Binary """
pic_bytes = b64decode(ico_b)  # trasform into bytes with Base64
image_1 = ImageTk.BytesIO(pic_bytes)  # create a pillow ImageTk from bytes
""" From String """
pic_bytes = b64decode(ico_s.encode())  # trasform into bytes with Base64
image_2 = ImageTk.BytesIO(pic_bytes)  # create a pillow ImageTk from bytes
""" Configuration """
pil_photo = Image.open(image_1)  # get the image with PIL Image
tk_photo = ImageTk.PhotoImage(
    pil_photo)  # convert to an image Tkinter can handle
label = Label(
    root, image=tk_photo).pack()  # display the image into tkinter interface

# Keep the program open:
root.mainloop()