Forum Archive

Now… Change the image in a UI...

nasadave

Using the same method recommended to change text in a label (previous post), I am now trying to change an image based on a photo taken by the camera. The program tries, but returns a blank image to the UI. The image is definitely being taken, because I can display it to the console - just not in the ImageView image on the UI.

Here's the code:

v=ui.load_view('MyUI')

v.present('sheet')

@ui.in_background

def getimage():

…myimage=photos.capture_image()

…imageview1=v['imageview1']

…myimage = myimage.resize((50,50),Image.BILINEAR)

…imageview.image=ui.Image(myImage)

getimage()

dgelessus

The issue here is that there is no built-in way to convert a PIL image (as returned by photos) to a ui.Image; doing ui.Image(some_pil_image) doesn't work. Here's how I managed to do the conversion, with the help of the StringIO module:

import StringIO
import ui

def pil_to_ui_image(img):
    strio = StringIO.StringIO()
    img.save(strio, img.format)
    data = strio.getvalue()
    strio.close()
    return ui.Image.from_data(data)

Calling the pil_to_ui_image() function with a PIL image as an argument will return an identical ui.Image.

nasadave

Figured it out. Needed to modify the last line in the def to:

imageview1.image=ui.Image.from_data(myimage)

That worked.

dgelessus

Fine, I suppose it also works that way..? I did not know that was possible. The documentation on that function says that it expects raw image data, not that it can also take a PIL image object.

nasadave

Oops, yes, you're correct. I had added this line in the def after posting the first time:

myimage = photos.get_image(raw_data=True)

nasadave

But thanks for your response… I will eventually need to know how to make a PIL conversion too!

[deleted]

@nasadave Or like this... http://omz-forums.appspot.com/pythonista/post/5232661803040768