Pergunta

I have a picture in memory a format (output from pyplot) and I want to directly show it on the Android through Kivy, but I don't want to create a picture file. Is there any way to do this? On pyplot I am able to generate the file like object by writing it the object, but I don't know how to put it into Kivy.

Foi útil?

Solução

You could save the file into a buffer with StringIO (see this: Binary buffer in Python).

Something like:

from StringIO import StringIO
buff = StringIO()
plt.savefig(buff)
buff.seek(0)
from kivy.core.image.img_pygame import ImageLoaderPygame
imgdata = ImageLoaderPygame(buff)._data

Outras dicas

Similar to the first answer but doesn't require img_pygame:

    from kivy.core.image import Image as CoreImage
    from kivy.uix.image import Image
    import io
    import qrcode # specific to my usecase, interchangeable with Pil.Image
    # OR
    from PIL import Image as PilImage


    msg = "text"
    image = Image(source="")
    imgIO = io.BytesIO()
    qr = qrcode.make(msg) # returns PilImage object
    qr.save(imgIO, ext='png') # equivalent to Pil.Image.save()
    imgIO.seek(0)
    imgData = io.BytesIO(imgIO.read())
    image.texture = CoreImage(imgData, ext='png').texture
    image.reload()

If you want to display a binary image directly into kivy you can simply work with io module (import io) and kivy image module (kivy.uix.image)

Check this code:

from kivy.uix.image import Image, CoreImage
import io

f=open("img.jpg",'rb')

binary_data= f.read() #image opened in binary mode

data = io.BytesIO(binary_data)
img=CoreImage(data, ext="png").texture

new_img= Image()
new_img.texture= img
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top