pyqt5 uses sqlite3 to read pictures and store them in the database and read pictures from the database for display

interface code

This part is directly generated. For details, please refer to my other blogs. The
general interface is as follows. The middle "IMG SHOW" is used to display the pictures in the database later. The two buttons are to open the pictures and store them in the database and from the database. read image for display
insert image description here

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Finger_UI.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(773, 529)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton_OpenFile = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_OpenFile.setGeometry(QtCore.QRect(150, 300, 131, 41))
        self.pushButton_OpenFile.setObjectName("pushButton_OpenFile")
        self.label_ShowImg = QtWidgets.QLabel(self.centralwidget)
        self.label_ShowImg.setGeometry(QtCore.QRect(230, 30, 251, 221))
        self.label_ShowImg.setAlignment(QtCore.Qt.AlignCenter)
        self.label_ShowImg.setObjectName("label_ShowImg")
        self.pushButton_read_db = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_read_db.setGeometry(QtCore.QRect(420, 300, 131, 41))
        self.pushButton_read_db.setObjectName("pushButton_read_db")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 773, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_OpenFile.setText(_translate("MainWindow", "打开文件夹"))
        self.label_ShowImg.setText(_translate("MainWindow", "IMG SHOW"))
        self.pushButton_read_db.setText(_translate("MainWindow", "读取数据库"))

main function

The main function part clearly records how to use sqlite3 in pyqt, you can directly read the code without too much explanation.

from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow,QApplication
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtSql import QSqlDatabase,QSqlQuery,QSqlTableModel
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox,QTableView

import sys
import cv2
import base64
import sqlite3

import Finger_UI


class Main_window(QtWidgets.QMainWindow,Finger_UI.Ui_MainWindow):
    def __init__(self,parent=None):
        super(Main_window,self).__init__(parent)
        self.setupUi(self)

        self.db_connect()
        self.createTable()

        self.pushButton_OpenFile.clicked.connect(self.open_save)
        self.pushButton_read_db.clicked.connect(self.show_img)

    def db_connect(self):
        self.conn = sqlite3.connect('./test.db')
        self.cursor = self.conn.cursor()

    def createTable(self):
        table_name = "pictureTable"
        self.cursor.execute(
            "create table IF NOT EXISTS %s(picName TEXT,width INTEGER, height INTEGER, image_bytes BLOB)"
                   % table_name)
        self.conn.commit()

    def save_img2db(self,img_name_path):
        image = cv2.imread(img_name_path)
        # 获取图像的宽度和高度
        height, width, _ = image.shape
        # 将图像编码为 PNG 格式的字节数据
        retval, encoded_image = cv2.imencode(".jpg", image)
        content = base64.b64encode(encoded_image)
        # 插入图片的二进制数据和相关信息
        name = img_name_path.split('/')[-1]
        sql = f"INSERT INTO pictureTable (picName, width, height, image_bytes) VALUES (?, ?, ?, ?);"
        self.cursor.execute(sql, (name, width, height, content))
        self.conn.commit()

    def read_img_from_db(self):
        sql = f"SELECT image_bytes FROM pictureTable WHERE picName=?"
        self.cursor.execute(sql, ('test.jpg',))
        value = self.cursor.fetchone()
        if value:
            img_data = base64.b64decode(value[0])
            # 如果是用cv2显示还需要做的处理
            # 将open方法读取的字节码转为opencv格式的数据
            # nparr = np.fromstring(img_data, np.uint8)
            # img_decode = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            return img_data
        else:
            return None


    def show_img(self):
        img_data = self.read_img_from_db()
        if img_data:
            pixmap = QtGui.QPixmap()
            pixmap.loadFromData(img_data)
            scaled_pixmap = pixmap.scaled(self.label_ShowImg.size(), QtCore.Qt.AspectRatioMode.KeepAspectRatio)
            self.label_ShowImg.setPixmap(scaled_pixmap)
        else:
            QMessageBox.warning(self, 'Image Retrieval', 'No image found in the database.')


        # 如果直接从文件读取用这种方式显示
        # img = QtGui.QPixmap(imgName).scaled(self.label_ShowImg.width(), self.label_ShowImg.height())
        # self.label_ShowImg.setPixmap(img)


    # 窗口关闭时关闭数据库
    def closeEvent(self, QCloseEvent):
        self.conn.close()

    def open_save(self):
        imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
        if imgName:
            self.save_img2db(imgName)




    def open_file(self):
        fileName1, filetype = QFileDialog.getOpenFileName(self,
                                                          "选取模板文件文件",
                                                          "./",
                                                          "All Files (*);;Text Files (*.txt)")  # 设置文件扩展名过滤,注意用双分号间隔
        print("fileName1:",fileName1, filetype)








if __name__ == '__main__':
    app = QApplication(sys.argv)
    mytest = Main_window()
    mytest.show()
    app.exec_()

Show results

run the main function

read image into

Click "Open Folder", select a picture, and after reading it, you can see it in the database. What you see on the
insert image description here
database interface
insert image description here

read image and display

Click "After reading the database, you can directly read the corresponding file from the database", see the main function code for details
insert image description here

Guess you like

Origin blog.csdn.net/qin_liang/article/details/131007482