Python 从图像创建缩略图并将其作为blob插入SQLite
我想从图像创建一个缩略图,然后将该缩略图作为BLOB插入SQLite。(不先将缩略图保存为文件) 我的代码Python 从图像创建缩略图并将其作为blob插入SQLite,python,sqlite,blob,Python,Sqlite,Blob,我想从图像创建一个缩略图,然后将该缩略图作为BLOB插入SQLite。(不先将缩略图保存为文件) 我的代码 from PIL import Image size = 120,120 file = "a.jpg" imgobj = Image.open(file) imgobj.thumbnail(size) 但是如何将其保存为BLOB到SQLite呢?有很多方法,这是其中之一: import sqlite3 from PIL import Image size = 1
from PIL import Image
size = 120,120
file = "a.jpg"
imgobj = Image.open(file)
imgobj.thumbnail(size)
但是如何将其保存为BLOB到SQLite呢?有很多方法,这是其中之一:
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.
[buffer(imgobj.tostring())]成功了。万分感谢!!差不多完成了,但是有一个奇怪的错误。我更改了这个:cur.execute(“创建表img(f text,x blob)”)cur.execute(“插入img(f,x)值(?,)”,file,[buffer(imgobj.tostring())]),但我收到一个错误:cur.execute(“插入img(f,x)值(?,)”,file,[buffer(imgobj.tostring())])类型错误:函数最多使用2个参数(给定3个)以这种方式更改时:cur.execute(“创建表img(f text,x blob)”)cur.execute(“插入到img(f,x)值(?,)”,(文件,[buffer(imgobj.tostring())]))错误是:cur.execute(“插入到img(f,x)值(?,,(文件,[buffer(imgobj.tostring())]))InterfaceError:绑定参数1时出错-可能不支持类型。修复:删除方括号[]->cur.execute(“插入到img(f,x)值(?,)”,(文件,缓冲区(imgobj.tostring()))