how to display an image in tkinter from a byte array

2.8k Views Asked by At

i scraped from the web some pictures with aiohttp and i got them saved in a list filled with arrays like this('\xe25\xd7\xeeP{\x08\x18-6\x809\xabQ1LQ\xf0\x02hC\x11\x97*.\xc8...')

i am trying to display the pictures using canvas and Photoimage but it doesnt work

here are some fragments of my code, thanks in advance and sorry for my english

bytesfoto=self.fotobytes[indice]
    img = ImageTk.PhotoImage(Image.open(BytesIO(bytesfoto)))
    self.canvas.create_image(20, 20, anchor=NW, image=img)



 self.canvas = Canvas(width=300, height=300)

    self.canvas.grid(row=2, column=1)
2

There are 2 best solutions below

0
Darius Lehmann On

There is a sort of workaround but its not that nice: you can save each Image as a jpg and then reopen then with PIL to then display then with Photoimage but that requires the python program to save the images. I save them like this:

with open(r"example.jpg", 'wb') as f:

    f.write(list_arrays[0])

and then display that image using PhotoImage:

root = tk.Tk()

image = PIL.Image.open("example.jpg")

photo = PIL.ImageTk.PhotoImage(image)

ttk.Label(root,image=photo).pack()

root.mainloop()

this is not a solution but rather a workaround but i hope it helps

0
Gregor Maclaine On

You can initialise the Tkinter PhotoImage class using bytes as long as you provide the file format with it as such:

image_content = b'...' # Data you scraped from some URL
file_format = 'jpg' # The file extension of the sourced data

canvas = tk.Canvas(window, width=300, height=300)
canvas.pack()
img = tk.PhotoImage(data=image_content, format=file_format)
canvas.create_image(20, 20, anchor=tk.NW, image=img)