Retrieve image from sqlite3 and display in Kivy image widget - ValueError

♀尐吖头ヾ 提交于 2019-12-11 15:18:47

问题


REQUIREMENT

I'm trying to retrieve an image from Database and set this image to kivy image widget, this operation throws a ValueError, unsure of the cause. Welcome any inputs.

Database: Sqlite3

Table name: Users

Columns: 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

ERROR TRACEBACK:

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:


After execution of io.BytesIO(), data is in Bytes. Use Kivy CoreImage and texture to convert data.

Replace

self.image.source = data

with:

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

Image source

source

Filename / source of your image.

source is a StringProperty and defaults to None

Output




回答2:


Ikolim's answer is good but to be more specific, 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


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


来源:https://stackoverflow.com/questions/51758975/retrieve-image-from-sqlite3-and-display-in-kivy-image-widget-valueerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!