Create thumbnail from image and insert in SQLite a

2019-04-17 00:00发布

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条回答
该账号已被封号
2楼-- · 2019-04-17 00:39

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.
查看更多
登录 后发表回答