Create thumbnail from image and insert in SQLite as blob

放肆的年华 提交于 2019-12-22 01:43:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!