【问题标题】:python-kivy show images by data stored in a variablepython-kivy 通过存储在变量中的数据显示图像
【发布时间】:2021-06-03 23:10:32
【问题描述】:

我有没有如下所示的方法,

from kivy.uix.image import Image
from kivy.uix.gridlayout import GridLayout
root=GridLayout(cols=2)
image="all image data as a string"
image=Image(source=image)
root.add_widget(image)
runTouchApp(root)

我试过了,但它只需要图像路径 为什么我这样做是因为我正在做一个应用程序,以便将图像数据作为字符串存储在数据库中,并且我想显示该图像而不将其存储在设备存储中

【问题讨论】:

    标签: python database image kivy


    【解决方案1】:

    您可以尝试将数据包装在BytesIO 对象中并将其作为source 传递,如果它不起作用(现在无法测试)您应该可以使用core.image.Image(@ 987654321@),然后使用此图像的texture 属性分配给kivy.uix.image.Image 实例。

    编辑:这是一个从内存加载图像的示例,这里使用枕头构造它并将其作为 BytesIO 对象获取,但您可以从数据库中获取源数据。

    from io import BytesIO
    from pathlib import Path
    
    from kivy.app import App
    from kivy.core.image import Image as CoreImage
    from kivy.uix.image import Image
    # NOTE this import is important to ensure kivy is ready to load an image from memory
    from kivy.core.window import Window
    from PIL import Image as PillowImage, ImageDraw
    
    WIDTH = 1000
    
    class Application(App):
        def build(self):
            # create a pillow image
            pillow_image = PillowImage.new(mode='RGBA', size=(WIDTH, WIDTH))
            draw = ImageDraw.Draw(pillow_image)
            for x in range(0, WIDTH, 5):
                draw.line((0, x, x, WIDTH), fill=(x, x, x, 255))
                draw.line((x, WIDTH, WIDTH, WIDTH - x), fill=(x, x, x, 255))
    
                draw.line((WIDTH, WIDTH - x, WIDTH - x, 0), fill=(x, x, x, 255))
                draw.line((WIDTH - x, 0, 0, x), fill=(x, x, x, 255))
    
            # create bytes from the image data
            image_bytes = BytesIO()
            pillow_image.save(image_bytes, format='png')
            image_bytes.seek(0)
    
            # load image data in a kivy texture
            core_image = CoreImage(image_bytes, ext='png')
            texture = core_image.texture
            img = Image(texture=texture)
            return img
    
    
    if __name__ == "__main__":
        Application().run()
    

    【讨论】:

      【解决方案2】:

      您可以使用图像数据创建Texture,然后将该Texture 分配给Image。请参阅 TextureImage 的文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-17
        • 2019-05-31
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        • 2014-09-06
        相关资源
        最近更新 更多