1
import base64
from tkinter import *
from PIL import ImageTk,Image

imgstring="/9j/4AAQSkZJRgABAQEASABIAAD/4QCMRXhpZgAASUAADADEBFAH/2Q=="
imgdata = base64.b64decode(imgstring)

imgfinal = open('here.jpg','wb')
imgfinal.write(imgdata)


root=Tk()
img = ImageTk.PhotoImage(Image.open(imgdata)) #This Doesn't work for me !
panel = Label(root,image=img)
panel.pack()
root.mainloop()

What I am trying to do is to add an image to the gui from the python script itself.
The imgstring variable is a shortened version of the actual image code.
The "here.jpg" file is a test used to make sure the code actually converts the imgdata bytes into an image.

Edit: -How can I add the image from its string to the label ?
-What should I change the line " img = ImageTk.PhotoImage.. " to ?

Community
  • 1
  • 1
usersina
  • 1,063
  • 11
  • 28

1 Answers1

2

Tkinter PhotoImage() accepts a base64 string as input:

from tkinter import *

root=Tk()
imgstring = "/9j/4AAQSkZJRgABAQEASABIAAD/4QCMRXhpZgAASUAADADEBFAH/2Q=="
img = PhotoImage(data=imgstring)
panel = Label(root,image=img)
panel.pack()

root.mainloop()
figbeam
  • 7,001
  • 2
  • 12
  • 18
  • 1
    If the image is a .jpg as suggested by the name 'here.jpg' in the question, then it won't work since tkinter doesn't support this format but this solution would work for a .png image. – j_4321 Dec 11 '18 at 16:05
  • How are they any different ? I used an online jpg to png converter and then looked at their code with notepad after encoding both of them to base64. There is no difference. EDIT: The online converter was faulty, it didn't do anything aside from renaming the .jpg to .png – usersina Dec 11 '18 at 18:27
  • You don't need to save it to a file, just use the `img` in your label. I have updated my example. – figbeam Dec 11 '18 at 18:41