我想从图像创建缩略图,然后将该缩略图插入到SQLite中作为BLOB。 (不首先将缩略图保存为文件)
我的代码;
from PIL import Image
size = 120,120
file = "a.jpg"
imgobj = Image.open(file)
imgobj.thumbnail(size)
但是如何将它作为BLOB保存到SQLite
答案 0 :(得分:2)
嗯,有很多方法,这是其中之一:
import sqlite3
from PIL import Image
size = 120, 120
file = "/tmp/a.jpg"
imgobj = Image.open(file)
imgobj.thumbnail(size)
con = sqlite3.connect("/tmp/imagesdb")
cur = con.cursor()
cur.execute("create table img (x blob)")
cur.execute("insert into img(x) values(?)", [ buffer(imgobj.tostring()) ] )
con.commit()
cur.close()
con.close()
# read it back.
con = sqlite3.connect("/tmp/imagesdb")
cur = con.cursor()
row = cur.execute('SELECT * FROM img')
for item in row:
print item #dont worry just pointers to files...
#print item[0] # has actually binary contents.