从sqlite3数据库检索图像,并直接显示在kivy窗口 [英] Retrieve Image from sqlite3 database and directly display on kivy window
问题描述
我从此代码获得了什么?
从数据库中检索图片,然后从
这个代码
与open(self.filename,'wb')作为output_file:
output_file.write .ablob)
那么只有我可以访问该图像。
我不能直接从数据库获取图像并显示它。
$ b
当我点击 id:display_picture ,那么具有 id:image 的图片列应直接从数据库显示图片,而无需先在同一个文件夹中创建。
请参阅下面的图片,了解我想要什么:
main.py文件
来自kivy.app import App
/ pre>
import sqlite3
import os.path
from kivy.uix.boxlayout import BoxLayout
类数据库(BoxLayout):
def __init __(self,** kwargs):
super(Database,self) .__ init __(** kwargs)
self.cols = 2
def on_release(self):
try:
self.conn = sqlite3.connect .db')
printdone
self.sql ='''如果不存在则创建表sample(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
PICTURE BLOB,
$ TYPE,
FILE_NAME TEXT);'''
try:
self.conn.execute(self.sql)
printcreated table
except:
printalready there
except:
printfail
def insert_picture(self,conn,picture_file):
open(picture_file,'rb')as input_file:
ablob = input_file.read()
base = os.path.basename(picture_file)
afile,ext = os.path.splitext基础)
sql ='''INSERT INTO示例
(PICTURE,TYPE,FILE_NAME)
VALUES(?,?);'''
conn.execute ,[sqlite3.Binary(ablob),ext,afile])
printadded 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 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))
.id.label_picture.text = str(self.lista)
print self.ids.label_picture.text
class mainApp(App):
def build self):
return Database()
如果__name__ =='__main__':
mainApp()。run()
main.kv文件
< Database> ;:
/ pre>
BoxLayout:
orientation:'vertical'
Button:
size_hint:1,.2
text:到数据库
on_release:root.on_release()
GridLayout:
cols:2
按钮:
text:添加图片
on_release:root .on_picture_insert()
按钮:
id:display_picture
text:显示图片和显示名称
on_release:root.on_show_picture()
标签:
id:label_picture
text:Picture Name
Image:
id:image
source:team.jpg
点击按钮后显示图片和显示名称时所需的输出
>
编辑1:主要的是,如果图像直接从数据库访问,图像源将是什么?
解决方案你可以尝试sth like:(可以帮助你找出一个更好的方法)
kivy.core.image import Image as CoreImage
from kivy.uix.image import Image
import sqlite3 as lite
import io
#从db加载图像, CREATE TABLE Images(Id INTEGER PRIMARY KEY,Data BLOB); >这是db创建...
con = lite.connect('images.db')#假设images.db是一个sqlite3 db
with con:
cur = con.cursor()
cur.execute(SELECT Data FROM Images;)#png是图像扩展
blob_data = cur.fetchone()[0]#仅获取一个图像数据
#从内存加载图像,如http://kivy.org/docs/api-kivy.core.image.html#in-memory-image-loading
data = io.BytesIO( blob_data)
im = CoreImage(data,ext =png)
#使用im作为图像的纹理,例如:
class LoadedImage
def __init __(self,** kwargs):
super(LoadedImage,self).__ init __(** kwargs)
self.texture = im.texture#using the texture
What I am getting from this code?
Image is retrieved from the database, then created in the same folder from this code
with open(self.filename, 'wb') as output_file: output_file.write(self.ablob)
then only I can get access to that image. I cannot directly get the image from the database and display it.
What I want to get?
When I click on button with id: display_picture then the Image column with id: image should display the image directly from the database without first being created in the same folder.
Please see the image below to get an idea of what I want
main.py file
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 file
<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"
Desired output after click on button (Show picture and display names)
EDIT 1: The main thing is that, what would be the image source if the image is accessed directly from the database?
解决方案well you can try sth like : (may help you figure out a better way)
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
这篇关于从sqlite3数据库检索图像,并直接显示在kivy窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!