【问题标题】:How do I store a picture in a table with python-sqlite3?如何使用 python-sqlite3 将图片存储在表中?
【发布时间】:2023-03-25 21:01:01
【问题描述】:

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

【问题讨论】:

  • 您必须将该图片转换为 base64 图像。然后将base64字符串存储到数据库中

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


【解决方案1】:

您可以将其编码为 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()

【讨论】:

  • 谢谢。我再问你一个问题。你知道如何在一个字段中保存 20 张图片吗?
  • 听起来不太合理。你应该重新考虑你的数据库结构:)
【解决方案2】:

对图像数据使用blob类型很好。存储的数据 使用 sqlite.Binary 类型。

【讨论】:

    【解决方案3】:

    我在学习 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 2012-06-23
      相关资源
      最近更新 更多