sqlite3,图片的读写及显示

# encoding: utf-8
import sqlite3
from io import BytesIO
from PIL import Image
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg


# pil
def bytes_pil_img(bytes):
    # convert to byte
    # print(bytes[:50])
    bytes_stream = BytesIO(bytes)
    # print(bytes_stream)
    roiimg = Image.open(bytes_stream)
    roiimg.show()  # 展示图片


# plt
def bytes_plt_img(bytes):
    bytes_stream = BytesIO(bytes)
    roiimg = mpimg.imread(bytes_stream)
    plt.imshow(roiimg)  # 显示图片
    plt.axis('off')  # 不显示坐标轴
    plt.show()


def save_image(res):
    with open(r'233.png', 'wb') as f:
        f.write(res)


def mdx2db(dbname, paraList, pathbase):
    if os.path.isfile(dbname):
        os.remove(dbname)
    conn = sqlite3.connect(dbname)
    c = conn.cursor()
    c.execute('''CREATE TABLE pics
        (ID INTEGER PRIMARY KEY  AUTOINCREMENT,
        tupian          TEXT    ,
        geshi          TEXT    ,
        image          blob     
         );''')
    conn.commit()
    for item in paraList:
        msql = '''INSERT INTO pics (tupian,geshi,image ) VALUES (?,?,?)'''

        filename, file_extension = os.path.splitext(item)
        imgPath = pathbase + '/' + item
        with open(imgPath, 'rb') as input_file:
            image = input_file.read()

        para = (filename, file_extension, image)
        c.execute(msql, para)
        c.execute('select image from pics')
        res = c.fetchall()[0][0]
        # save_image(res)
        # bytes_pil_img(res)
        bytes_plt_img(res)
    conn.commit()
    conn.close()


mdx2db('demo.db', ['2.png'], r'C:\Users\demokey\Desktop')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值