【发布时间】:2023-03-25 21:01:01
【问题描述】:
我正在尝试将图片存储在 sqlite3 表中。我正在使用 python 和 sqlite3。 如果您有示例代码或如何将图片保存到 sqlite3 表中,请告诉我。
【问题讨论】:
-
您必须将该图片转换为 base64 图像。然后将base64字符串存储到数据库中
标签: python database python-3.x sqlite sql-insert
我正在尝试将图片存储在 sqlite3 表中。我正在使用 python 和 sqlite3。 如果您有示例代码或如何将图片保存到 sqlite3 表中,请告诉我。
【问题讨论】:
标签: python database python-3.x sqlite sql-insert
您可以将其编码为 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()
【讨论】:
对图像数据使用blob类型很好。存储的数据 使用 sqlite.Binary 类型。
【讨论】:
我在学习 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()
【讨论】: