Forum Archive

Can I save ui.Image as a jpeg file ?

satsuki.kojima

Can I save ui.Image as an external file with the format of jpeg (or png). If I can transform ui.Image into PIL Image, that would do.

What I want to do is snapshot an image on ui.View and save that image as a jpeg file.
Here is my code and I can only make a ui.Image, but don’t know how to make a jpeg file from it.

with ui.ImageContext(100, 100) as ctx:
...
... v = ui.ImageView(width=100,height=100)
... label = ui.Label(text='testlabel')
... v.add_subview(label)
... v.draw_snapshot()
... label_img= ctx.get_image()
...
type(label_img)

cvp

To convert pil image to ui.Image

def ui2pil(ui_img):
  return Image.open(io.BytesIO(ui_img.to_png()))

To save it as a xxxxxx.jpg filename

            pil.save(filename, quality=95)
satsuki.kojima

@cvp
Thank you. I could make a png external file.
Now, I have another problem. I thought png file would do, but I wanted to combine the image with a photo pictures which are usually in jpeg. When I try it with paste method of PIL, such as

photo_img.paste(img_labels)

where photo_img is in jpeg format and img_labels is in png format, this will result an error “images do not match.”
If you think of any good solution, let me know. Thank you.

cvp

@satsuki.kojima try

from PIL import Image

pil1 = Image.open('test:Lenna')
pil2 = Image.open('sprite.png').convert('RGBA')
w,h = pil2.size
pil1.paste(pil2,box=(w,h))

pil1.show()
satsuki.kojima

@cvp

Now, I can make it a PIL image this way. Thank you so much.