如何使用python-sqlite3将图片存储在表中?

时间:2018-08-10 05:31:02

标签: python database python-3.x sqlite sql-insert

我正在尝试将图片存储在sqlite3表中。我正在使用python和sqlite3。 如果您有示例代码或如何将图片保存到sqlite3表,请告诉我。

3 个答案:

答案 0 :(得分:1)

对图像数据使用斑点类型很好。存储的数据 使用 sqlite.Binar y类型。

答案 1 :(得分:0)

到目前为止,您尝试了什么? 您可以将其编码为base64字符串(如Yogesh所述),也可以尝试存储二进制文件。

import sqlite3
import base64

conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE images (image text)''')

# binary
c.execute("INSERT INTO images VALUES ({})".format(sqlite3.Binary(file.read())))

# base64
c.execute("INSERT INTO images VALUES ({})".format(base64.b64encode(file.read())))

conn.commit()
conn.close()

答案 2 :(得分:0)

学习sqlite3时,我编写了一个简单的代码来管理少量图像。有点长而急促,但它可以工作。希望它对您有用

#!/usr/bin/env
from skimage import io, filters

import warnings, os

import numpy as np

import sqlite3

warnings.filterwarnings('ignore')

class SqliteImage(object):

def __init__(self, databaseDir):
    self.databaseDir = databaseDir
    self.conn = sqlite3.connect(databaseDir)
    self.cur = self.conn.cursor()

def createTable(self, table):
    self.cur.execute(""" CREATE TABLE %s (
                name     TEXT PRIMARY KEY,
                content  TEXT,
                oldShape INT
                )""" % table)

def delete(self, table):
    self.cur.execute('DROP TABLE %s' %table)

# put images into sqlite3
def shapeToStr(self, arr):
    return ' '.join([str(item) for item in arr])
def saveImage(self, path):
    img = io.imread(path)
    newShape = [1]
    oldShape = img.shape
    for val in oldShape:
        newShape[0] *= val
    img = np.array(img.reshape(newShape), dtype=str)
    img = ' '.join(img)
    self.cur.execute('INSERT INTO img VALUES (?, ?, ?)', 
            [str(os.path.basename(path)), img, self.shapeToStr(oldShape)] )

# get images from sqlite3
def dec(self, name):
    return "\'"+name+"\'"

def getImage(self, name):
    self.cur.execute(("SELECT name, content, oldShape FROM img WHERE name=%s;" % self.dec(name)))
    # print([item[0] for item in cur.description])
    for basename, img, oldShape in self.cur.fetchall():
        oldShape = [int(item) for item in oldShape.strip().split()]
        img = np.array(img.strip().split(), dtype=int)
        img = img.reshape(oldShape)
        print(basename)
        io.imshow(img)
        io.show()

def close(self):
    self.conn.commit()
    self.conn.close()

# test
db = SqliteImage('images.db')
db.saveImage(os.path.join(r'C:\Users\Administrator\Desktop', 'crocodile.jpg'))
db.getImage('crocodile.jpg')
db.saveImage(os.path.join(r'C:\Users\Administrator\Desktop', 'bear.jpg'))
db.getImage('bear.jpg')
db.close()
相关问题