【问题标题】:Retrieve image from sqlite3 and display in Kivy image widget - ValueError从 sqlite3 检索图像并在 Kivy 图像小部件中显示 - ValueError
【发布时间】:2019-01-16 10:39:40
【问题描述】:

要求

我正在尝试从数据库中检索图像并将此图像设置为 kivy 图像小部件,此操作会引发 ValueError,不确定原因。欢迎任何意见。

数据库:Sqlite3

表名:用户

列:用户 ID、用户名、用户图像

   def populate_fields(self): # NEW
      # Code retrieves text data and display in textinput fields here.

      # STEP 1: RETRIEVE IMAGE
      connection = sqlite3.connect("demo.db")
      with connection:
          cursor = connection.cursor()
          cursor.execute("SELECT UserImage from Users where 
          UserID=?",self.data_items[columns[0]]['text'] )
          image = cursor.fetchone()
          data = io.BytesIO(image[0])

      #STEP 2: SET OUTPUT TO IMAGE WIDGET
          self.image.source = data # ---> triggers an Error

错误追溯:

self.image.source = data
   File "kivy\weakproxy.pyx", line 33, in kivy.weakproxy.WeakProxy.__setattr__ (kivy\weakproxy.c:1471)
   File "kivy\properties.pyx", line 478, in kivy.properties.Property.__set__ (kivy\properties.c:5572)
   File "kivy\properties.pyx", line 513, in kivy.properties.Property.set (kivy\properties.c:6352)
   File "kivy\properties.pyx", line 504, in kivy.properties.Property.set (kivy\properties.c:6173)
   File "kivy\properties.pyx", line 676, in kivy.properties.StringProperty.check (kivy\properties.c:8613)
 ValueError: Image.source accept only str

【问题讨论】:

    标签: python image sqlite kivy kivy-language


    【解决方案1】:

    io.BytesIO() 执行后,data 以字节为单位。使用 Kivy CoreImagetexture 转换 data

    替换

    self.image.source = data
    

    与:

    self.image.texture = CoreImage(data, ext="png").texture
    

    Image source

    source
    

    图片的文件名/来源。

    来源是StringProperty,默认为无

    输出

    【讨论】:

      【解决方案2】:

      Ikolim 的回答很好,但更具体地说, 如果你想直接在 kivy 中显示二进制图像,你可以简单地使用 io 模块 (import io) 和 kivy 图像模块 (kivy.uix.image)

      检查此代码:

      from kivy.uix.image import Image, CoreImage
      import io
      
      
      binary_data= #binary img extracted from sqlite
      
      data = io.BytesIO(binary_data)
      img=CoreImage(data, ext="png").texture
      
      new_img= Image()
      new_img.texture= img
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 2015-11-23
        • 1970-01-01
        • 2014-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多