1

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)
user109606
  • 51
  • 4
  • Please provide all the data for an entire (but very small) image in your question. – martineau Jan 06 '21 at 22:16
  • Bytes data should be something like `b'....'`. Also images have some signature at the beginning of the data, PNG: `b'\x89PNG...'`, JPG: `b'\xff\xd8\xff\xe0\x00\x10JFIF...'` and GIF: `b'GIF89a...'`. So the data shown in your question is not likely an image data. – acw1668 Jan 07 '21 at 03:57

2 Answers2

1

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

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

Zachiah
  • 1,750
  • 7
  • 28