python sqlite数据库存储图片_如何用python在sqlite数据库中存储jpg

本文展示了如何使用Python的sqlite3库在SQLite数据库中存储和检索JPEG图像。首先,通过`get_picture_list`获取图片文件列表,然后创建或打开数据库并建立表结构。接着,使用`insert_picture`函数将图片文件读取为二进制数据并插入数据库。最后,通过`extract_picture`函数从数据库中提取图片,并保存到本地。
摘要由CSDN通过智能技术生成

存储和检索blobimport sqlite3

import os.path

from os import listdir, getcwd

from IPython.core.display import Image

def get_picture_list(rel_path):

abs_path = os.path.join(os.getcwd(),rel_path)

print 'abs_path =', abs_path

dir_files = os.listdir(abs_path)

return dir_files

def create_or_open_db(db_file):

db_is_new = not os.path.exists(db_file)

conn = sqlite3.connect(db_file)

if db_is_new:

print 'Creating schema'

sql = '''create table if not exists PICTURES(

ID INTEGER PRIMARY KEY AUTOINCREMENT,

PICTURE BLOB,

TYPE TEXT,

FILE_NAME TEXT);'''

conn.execute(sql) # shortcut for conn.cursor().execute(sql)

else:

print 'Schema exists\n'

return conn

def insert_picture(conn, picture_file):

with open(picture_file, 'rb') as input_file:

ablob = input_file.read()

base=os.path.basename(picture_file)

afile, ext = os.path.splitext(base)

sql = '''INSERT INTO PICTURES

(PICTURE, TYPE, FILE_NAME)

VALUES(?, ?, ?);'''

conn.execute(sql,[sqlite3.Binary(ablob), ext, afile])

conn.commit()

def extract_picture(cursor, picture_id):

sql = "SELECT PICTURE, TYPE, FILE_NAME FROM PICTURES WHERE id = :id"

param = {'id': picture_id}

cursor.execute(sql, param)

ablob, ext, afile = cursor.fetchone()

filename = afile + ext

with open(filename, 'wb') as output_file:

output_file.write(ablob)

return filename

conn = create_or_open_db('picture_db.sqlite')

picture_file = "./pictures/Chrysanthemum50.jpg"

insert_picture(conn, picture_file)

conn.close()

conn = create_or_open_db('picture_db.sqlite')

cur = conn.cursor()

filename = extract_picture(cur, 1)

cur.close()

conn.close()

Image(filename='./'+filename)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值