【发布时间】:2015-06-13 12:33:39
【问题描述】:
我从这段代码中得到了什么?
从数据库中检索图像,然后在同一文件夹中创建 这段代码
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"
点击按钮后所需的输出(显示图片和显示名称)
编辑1:主要的是,如果直接从数据库访问图像,图像源是什么?
【问题讨论】:
-
是的,您可以从内存中获取图像并显示它,如此处所述kivy.org/docs/api-kivy.core.image.html#in-memory-image-loading
-
@Flns 这似乎没有多大帮助:/
标签: android python database sqlite kivy