Skip to content Skip to sidebar Skip to footer

Base64 String To Image In Tkinter

I have a image i'm using in my GUI and i dont want it as an external resource when i compile the .exe or to my .py. I figured i should encode it to a string, copy the string in th

Solution 1:

If you have base64-encoded data, you need to use the data argument. However, I don't think this will work for jpg. It will work for .gif images though.

This is what the canonical documentation says for the data option:

Specifies the contents of the image as a string. The string should contain binary data or, for some formats, base64-encoded data (this is currently guaranteed to be supported for GIF images). The format of the string must be one of those for which there is an image file format handler that will accept string data. If both the -data and -file options are specified, the -file option takes precedence.

Example

import Tkinter as tk

IMAGE_DATA = '''
    R0lGODlhEAAQALMAAAAAAP//AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAA\nAAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
    TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n
    '''

root = tk.Tk()
image = tk.PhotoImage(data=IMAGE_DATA)
label = tk.Label(root, image=image, padx=20, pady=20)
label.pack()

root.mainloop()

Solution 2:

Got a way:

Say image='abc' is the string of the image coded in b64.

def install():
    if not os.path.isfile("logo.jpg"):
        open('logo.jpg','wb').write(base64.b64decode(image))

Gonna run this in my main() function and if the image doesnt exist in the folder, it will be created. Afterwords you'll just load the image as normal:

self.img=Image.open('logo.jpg')
self.image=ImageTk.PhotoImage(self.img)

I havent found a solution not to save the image at all however.

Post a Comment for "Base64 String To Image In Tkinter"