1

I'm trying to get Kivy to load image which was saved in memory by PIL after editing. I'm using answers from this question as method: Load image from memory in Kivy.

However, it does not work. This is my code:

from PIL import Image as PIL_Image

from kivy.app import App
from kivy.core.image import Image as CoreImage
from kivy.uix.image import Image

import io

class MyApp(App):

    def build(self):

        image_from_memory = CoreImage(memory_saved_image, ext='png')
        image_to_show = Image(source='')
        image_to_show.texture = image_from_memory.texture

        return image_to_show

if __name__ == "__main__":
    
    memory_saved_image = io.BytesIO()

    pil_edited_image = PIL_Image.open('test.png')

    # some non-related PIL image editing in here

    pil_edited_image.save(memory_saved_image, 'png')

    MyApp().run()

And this is my error message, including related log-message:

[WARNING] [Image       ] Unable to load image <<_io.BytesIO object at 0x000000000372F108>>
 Traceback (most recent call last):
   File "c:/Users/Вова/Desktop/SO example.py", line 26, in <module>
     MyApp().run()
   File "C:\Users\Вова\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\app.py", line 829, in run
     root = self.build()
   File "c:/Users/Вова/Desktop/SO example.py", line 13, in build
     image_from_memory = CoreImage(memory_saved_image, ext='png')
   File "C:\Users\Вова\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\core\image\__init__.py", line 547, in __init__
     self.load_memory(arg, ext, filename)
   File "C:\Users\Вова\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\core\image\__init__.py", line 783, in load_memory
     keep_data=self._keep_data)
   File "C:\Users\Вова\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\core\image\__init__.py", line 221, in __init__
     self._data = self.load(kwargs.get('rawdata'))
   File "C:\Users\Вова\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\core\image\img_sdl2.py", line 47, in load
     raise Exception('SDL2: Unable to load image')
 Exception: SDL2: Unable to load image

When I try to open this image from memory using PIL, it works, so the memory is not corrupt.

1 Answers1

0

Apparently, PIL does not reset the pointer when writing into io.BytesIO object.

Adding memory_saved_image.seek(0) before image_from_memory = CoreImage(memory_saved_image, ext='png') helped.