1

I'm trying to create PPM Tkinter.PhotoImage objects from data read out of memory. It works when I write the PPM data to a temporary file, but not when I read it directly from memory. In the latter case the computer complains that I'm giving it "truncated PPM data." However, reading from memory works fine when I'm working with GIFs. Can we get rid of whatever phenomenon is causing the truncation, maybe by padding the data I'm working with at the end?

If you're wondering why I don't just use ImageTk.PhotoImage from PIL, it's because doing so causes me a seg fault, apparently because I'm on a Mac.

I've attached a sample image although the phenomenon seems to occur no matter what image I'm working with.

from __future__ import absolute_import, division, print_function, unicode_literals

import Image, cStringIO, Tkinter, base64

window = Tkinter.Tk()
im_jpg = Image.open("Test.JPG")

data_ppm = cStringIO.StringIO()
data_gif = cStringIO.StringIO()
im_jpg.save(data_ppm, format="PPM")
im_jpg.save(data_gif, format="GIF")
im_jpg.save("Test.PPM", format="PPM")
data_ppm.seek(0)
data_gif.seek(0)
Image.open(data_ppm).show() # Works
Image.open(data_gif).show() # Works

# This works:
Tkinter.PhotoImage(master=window, data=base64.b64encode(data_gif.getvalue()), format="GIF")

# This works:
Tkinter.PhotoImage(master=window, file="Test.PPM", format="PPM")

assert open("Test.PPM", "rb").read() == data_ppm.getvalue() # Passes

# Doesn't work (and still doesn't work if I use base64.b64encode):
try:
    Tkinter.PhotoImage(master=window, data=data_ppm.getvalue(), format="PPM")
except Tkinter.TclError as te:
    print(te) # "Truncated PPM data"

Sample image

Community
  • 1
  • 1
kuzzooroo
  • 6,788
  • 11
  • 46
  • 84

1 Answers1

1

Tkinter does work with data='' provided the image data is in utf-8 format. I have some stored images in a python project so I don't need to have images as separate files.

To do this:

  1. Open the file you want to store in a python file in a console as latin1 and convert it to utf-8.

    file = open('cross-button.ppm', encoding='latin1')
    data = file.read()
    file.close()
    data.encode('utf-8')
    
  2. Store the data that is printed to your console in your python file which should start with # -- coding: utf-8 --. Make sure that if you copy it and newlines get added to the string you remove them.

    image = b'P6\n16 16\n255\n\xc3\xbf\xc3\xbf\xc3...'
    
  3. Then if you use this data everything will work. But only if you saved the utf-8 data, the latin1 data will cause the "Truncated PPM Data" error.

    PhotoImage(data=image)
    
Jayden
  • 26
  • 1