代码之家  ›  专栏  ›  技术社区  ›  Berch

从sqlite3检索图像并在Kivy图像小部件中显示-ValueError

  •  0
  • Berch  · 技术社区  · 6 年前

    要求

    我试图从数据库中检索一个图像,并将此图像设置为kivy图像小部件,此操作抛出一个ValueError,不确定原因。欢迎任何意见。

    数据库:Sqlite3

    表名:用户

    列:UserID、UserName、UserImage

       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
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   ikolim    6 年前

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

    替换

    self.image.source = data
    

    使用:

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

    Image source

    source
    

    图像的文件名/源。

    来源是 StringProperty 默认为无

    输出

    Img01 Img02

        2
  •  0
  •   Majd    5 年前

    伊科利姆的回答很好,但更具体地说, 如果您想直接将二进制图像显示到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