问题
I'd like to create a thumbnail from an image and then insert that thumbnail in SQLite as BLOB. (without saving thumbnail as file first)
My code;
from PIL import Image
size = 120,120
file = "a.jpg"
imgobj = Image.open(file)
imgobj.thumbnail(size)
But how to save it to SQLite as BLOB
回答1:
Well, there are many ways, and this is one of them:
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.
来源:https://stackoverflow.com/questions/21350415/create-thumbnail-from-image-and-insert-in-sqlite-as-blob