从sqlite3数据库中检索图像并直接显示在kivy窗口上

时间:2015-06-13 12:33:40

标签: android python database sqlite kivy

我从这段代码中得到了什么?

从数据库中检索图像,然后在相同的文件夹中创建 这段代码

with open(self.filename, 'wb') as output_file:
    output_file.write(self.ablob)

然后只有我可以访问该图像。 我不能直接从数据库中获取图像并显示它。

我想要的是什么?

当我点击带有 id:display_picture 的按钮时,带有 id:image 的图像列应该直接从数据库显示图像而不首先在同一文件夹中创建

请参阅下面的图片,了解我想要的内容

main.py文件

from kivy.app import App
import sqlite3
import os.path
from kivy.uix.boxlayout import BoxLayout

class Database(BoxLayout):
    def __init__(self,**kwargs):
        super(Database,self).__init__(**kwargs)
        self.cols = 2

    def on_release(self):
        try:
            self.conn = sqlite3.connect('test.db')
            print "done"
            self.sql = '''create table if not exists sample(
            ID INTEGER PRIMARY KEY AUTOINCREMENT,
            PICTURE BLOB,
            TYPE TEXT,
            FILE_NAME TEXT);'''
            try: 
                self.conn.execute(self.sql)
                print "created table"
            except:
                print "already there"
        except:
            print"fail"


    def insert_picture(self,conn, picture_file):
        with open(picture_file, 'rb') as input_file:
            ablob = input_file.read()
            base=os.path.basename(picture_file)
            afile, ext = os.path.splitext(base)
            sql = '''INSERT INTO sample
            (PICTURE, TYPE, FILE_NAME)
            VALUES(?, ?, ?);'''
            conn.execute(sql,[sqlite3.Binary(ablob), ext, afile]) 
            print "added picture"
            self.conn.commit()

    def on_picture_insert(self):
        self.picture_file = './pictures/team.jpg'
        self.insert_picture(self.conn,self.picture_file)

    def extract_picture(self,cursor, picture_id):
        self.sql1 = "SELECT PICTURE, TYPE, FILE_NAME FROM sample WHERE id = :id"
        self.param = {'id': picture_id}
        for r in self.conn.execute(self.sql1,self.param):
            self.filename = r[2]+r[1]
            self.ablob = r[0]
        with open(self.filename, 'wb') as output_file:
            output_file.write(self.ablob)
        return self.filename

    def on_show_picture(self):
        self.cur = self.conn.cursor()
        self.filename = self.extract_picture(self.cur, 1)
        self.lista = []
        self.p = self.conn.execute("select FILE_NAME,TYPE from sample")
        for r in self.p:
            for i in r:
                self.lista.append(str(i))

            self.ids.label_picture.text = str(self.lista)
            print self.ids.label_picture.text

class mainApp(App):

    def build(self):
        return Database()

if __name__ == '__main__':
    mainApp().run()

main.kv文件

<Database>:
    BoxLayout:
        orientation: 'vertical'
        Button:
            size_hint: 1,.2
            text: "Connect to Databse"
            on_release: root.on_release()
        GridLayout:
            cols: 2
            Button:
                text: "Add picture"
                on_release: root.on_picture_insert()
            Button:
                id: display_picture
                text: "Show Picture and display names"
                on_release: root.on_show_picture()
            Label:
                id: label_picture
                text: "Picture Name"
            Image:
                id: image
                source: "team.jpg"

点击按钮后显示所需的输出(显示图片和显示名称)

enter image description here

编辑1:主要的是,如果直接从数据库访问图像,那么图像源是什么?

1 个答案:

答案 0 :(得分:1)

你可以尝试一下:(可以帮助你找到更好的方法)

from kivy.core.image import Image as CoreImage
from kivy.uix.image import Image
import sqlite3 as lite
import io

# load an image from db , CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB); > this was the db created ...

con = lite.connect('images.db') # assume images.db is an sqlite3 db
with con:
    cur = con.cursor()
    cur.execute("SELECT Data FROM Images;") # png is the image extension
    blob_data = cur.fetchone()[0] # fetching one image data only

# load image from memory , as in  http://kivy.org/docs/api-kivy.core.image.html#in-memory-image-loading
data = io.BytesIO(blob_data)
im = CoreImage(data, ext="png") 

# using im, as a texture for an Image , for example:
class LoadedImage(Image):
    def __init__(self, **kwargs):
        super(LoadedImage, self).__init__(**kwargs)
        self.texture = im.texture # using the texture