Using Sqlite database under Qt to realize image reading and writing display

Series Article Directory

提示:这里是该系列文章的所有文章的目录
Chapter 1: Connect Qt to Sqlite3 and use Qtableview to display data in real time, rewrite QSqlQueryModel to realize text centering
Chapter 2: Use Sqlite database under Qt to realize image reading and writing display



foreword

In the previous article of this series of articles, there is a related introduction and configuration of using Sqlite3 database in Qt, which is also relatively convenient to use. For details, please click the catalog link to view. Using the Sqlite database in Qt can save many types of data, and it can also be used to save images. Here we will describe the functions of saving and reading and displaying images, and display the relevant codes for everyone to learn. If there are any mistakes, please contact us. Welcome everyone to criticize and correct.

Project effect
Please add a picture description


提示:以下是本篇文章正文内容,下面案例可供参考

1. Initialize the database

Create a database with the date of the day in the constructor and open it, and create a data table named imageTable at the same time, add id, name (image name), data (image data), and timestamp (timestamp) to the table. , where the id will automatically increase with the amount of inserted data, and the subsequent search function is also realized by searching the id.

//以当天日期为名称创建数据库并打开
QString dbName = QDate::currentDate().toString("yyyyMMdd") + ".db";
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(dbName);
if(!m_db.open())
{
    
    
    QMessageBox::information(this,"提示",m_db.lastError().text());
    return;
}

//创建名为imageTable的数据表
QSqlQuery query(m_db);
if(!query.exec("CREATE TABLE IF NOT EXISTS imageTable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, data BLOB, timestamp TEXT)"))
{
    
    
    QMessageBox::information(this,"提示",query.lastError().text());
    return;
}

2. Get image data

Here, the method of simulating adding images is used to obtain image data, open the specified folder and select the images in it, and save the images to the database.

//从文件夹获取图像数据
void Widget::on_pb_getImage_clicked()
{
    
    
    //选择图像
    QString fileName = QFileDialog::getOpenFileName(this,"open file dialog","D:/QT/Project/my_Project/28_iamgeSqlite","jpg files(*.jpg)");
    if(fileName == "")
    {
    
    
        return;
    }

    //获取图像名
    m_imageName = QFileInfo(fileName).fileName();
    ui->lb_name->setText(m_imageName);

    //界面显示
    QImage image;
    image.load(fileName);
    ui->lb_image->setPixmap((QPixmap::fromImage(image)).scaled(ui->lb_image->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));

    //获取图像数据
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly))
    {
    
    
        QMessageBox::information(this,"提示",file.errorString());
        return;
    }
    m_imageData = file.readAll();
    file.close();
}

//保存图像到数据库
void Widget::on_pb_saveDb_clicked()
{
    
    
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    ui->lb_dateTime->setText(timestamp);

    //插入图像和时间戳
    QSqlQuery query(m_db);
    query.prepare("INSERT INTO imageTable (name, data, timestamp) VALUES (:name, :data, :timestamp)");
    query.bindValue(":name",m_imageName);
    query.bindValue(":data",m_imageData);
    query.bindValue(":timestamp",timestamp);
    if(!query.exec())
    {
    
    
        QMessageBox::information(this,"提示",query.lastError().text());
        return;
    }
    else
    {
    
    
        QMessageBox::information(this,"提示","保存成功!");
    }
}

3. Find the specified image

The SELECT search statement is used here to search for the specified image according to the id in the data table, obtain the image data and various parameters and display it on the interface. For more SQL statements, please refer to the reference article in the previous article of this series. Detailed SQLite tutorial.

//根据id提取图像
void Widget::getImageData(int id)
{
    
    
    QSqlQuery query(m_db);
    if(!query.exec(QString("SELECT name, data, timestamp FROM imageTable WHERE id = %1").arg(id)))
    {
    
    
        QMessageBox::information(this,"提示",query.lastError().text());
        return;
    }
    if(query.next())
    {
    
    
        //图像名
        QString imageName = query.value(0).toString();
        ui->lb_name->setText(imageName);

        //显示图像
        QByteArray imageData = query.value(1).toByteArray();
        QPixmap pixmap;
        if(pixmap.loadFromData(imageData))
        {
    
    
            ui->lb_image->setPixmap(pixmap.scaled(ui->lb_image->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
        }

        //时间戳
        QString timestamp = query.value(2).toString();
        ui->lb_dateTime->setText(timestamp);
    }
}

4. Example complete code

Don't forget to add the SQL module in the Qt project file (.pro file)! (QT += sql)
1.widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>
#include <QFileDialog>
#include <QDateTime>
#include <QMessageBox>
#include <QDebug>

QT_BEGIN_NAMESPACE
namespace Ui {
    
     class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    
    
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

    void initWidget();
    void getImageData(int id);

private slots:
    void on_pb_getImage_clicked();
    void on_pb_saveDb_clicked();
    void on_pb_find_clicked();
    void on_pb_last_clicked();
    void on_pb_next_clicked();

private:
    Ui::Widget *ui;

    QSqlDatabase m_db;        //数据库对象
    QString m_imageName;      //图像名
    QByteArray m_imageData;   //图像数据
};
#endif // WIDGET_H

2.widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    
    
    ui->setupUi(this);
    this->initWidget();
}

Widget::~Widget()
{
    
    
    delete ui;
}

//初始化界面
void Widget::initWidget()
{
    
    
    //初始化变量
    m_imageName = "";
    m_imageData = "";

    //以当天日期为名称创建数据库并打开
    QString dbName = QDate::currentDate().toString("yyyyMMdd") + ".db";
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName(dbName);
    if(!m_db.open())
    {
    
    
        QMessageBox::information(this,"提示",m_db.lastError().text());
        return;
    }

    //创建名为imageTable的数据表
    QSqlQuery query(m_db);
    if(!query.exec("CREATE TABLE IF NOT EXISTS imageTable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, data BLOB, timestamp TEXT)"))
    {
    
    
        QMessageBox::information(this,"提示",query.lastError().text());
        return;
    }
}

//根据id提取图像
void Widget::getImageData(int id)
{
    
    
    QSqlQuery query(m_db);
    if(!query.exec(QString("SELECT name, data, timestamp FROM imageTable WHERE id = %1").arg(id)))
    {
    
    
        QMessageBox::information(this,"提示",query.lastError().text());
        return;
    }
    if(query.next())
    {
    
    
        //图像名
        QString imageName = query.value(0).toString();
        ui->lb_name->setText(imageName);

        //显示图像
        QByteArray imageData = query.value(1).toByteArray();
        QPixmap pixmap;
        if(pixmap.loadFromData(imageData))
        {
    
    
            ui->lb_image->setPixmap(pixmap.scaled(ui->lb_image->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
        }

        //时间戳
        QString timestamp = query.value(2).toString();
        ui->lb_dateTime->setText(timestamp);
    }
}

//从文件夹获取图像数据
void Widget::on_pb_getImage_clicked()
{
    
    
    //选择图像
    QString fileName = QFileDialog::getOpenFileName(this,"open file dialog","D:/QT/Project/my_Project/28_iamgeSqlite","jpg files(*.jpg)");
    if(fileName == "")
    {
    
    
        return;
    }

    //获取图像名
    m_imageName = QFileInfo(fileName).fileName();
    ui->lb_name->setText(m_imageName);

    //界面显示
    QImage image;
    image.load(fileName);
    ui->lb_image->setPixmap((QPixmap::fromImage(image)).scaled(ui->lb_image->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));

    //获取图像数据
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly))
    {
    
    
        QMessageBox::information(this,"提示",file.errorString());
        return;
    }
    m_imageData = file.readAll();
    file.close();
}

//保存图像到数据库
void Widget::on_pb_saveDb_clicked()
{
    
    
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    ui->lb_dateTime->setText(timestamp);

    //插入图像和时间戳
    QSqlQuery query(m_db);
    query.prepare("INSERT INTO imageTable (name, data, timestamp) VALUES (:name, :data, :timestamp)");
    query.bindValue(":name",m_imageName);
    query.bindValue(":data",m_imageData);
    query.bindValue(":timestamp",timestamp);
    if(!query.exec())
    {
    
    
        QMessageBox::information(this,"提示",query.lastError().text());
        return;
    }
    else
    {
    
    
        QMessageBox::information(this,"提示","保存成功!");
    }
}

//查找指定图像
void Widget::on_pb_find_clicked()
{
    
    
    //判断是否输入正确
    int id = ui->le_id->text().toInt();

    //获取图像数
    QSqlQuery query(m_db);
    query.exec("SELECT COUNT(id) FROM imageTable");
    query.next();
    int idMax = query.value(0).toInt();
    qDebug()<<idMax;

    if(id < 1)
    {
    
    
        getImageData(1);
        ui->le_id->setText(QString::number(1));
        QMessageBox::information(this,"提示","id超限!");
    }
    else if(id > idMax)
    {
    
    
        getImageData(idMax);
        ui->le_id->setText(QString::number(idMax));
        QMessageBox::information(this,"提示","id超限!");
    }
    else
    {
    
    
        getImageData(idMax);
    }
}

//上一张
void Widget::on_pb_last_clicked()
{
    
    
    int id = ui->le_id->text().toInt();
    if(id <= 1)
    {
    
    
        getImageData(1);
        ui->le_id->setText(QString::number(1));
        QMessageBox::information(this,"提示","当前图像为第一张!");
        return;
    }
    int idLast = id-1;
    getImageData(idLast);
    ui->le_id->setText(QString::number(idLast));
}

//下一张
void Widget::on_pb_next_clicked()
{
    
    
    //获取图像数
    QSqlQuery query(m_db);
    query.exec("SELECT COUNT(id) FROM imageTable");
    query.next();
    int idMax = query.value(0).toInt();

    int id = ui->le_id->text().toInt();
    if(id >= idMax)
    {
    
    
        getImageData(idMax);
        ui->le_id->setText(QString::number(idMax));
        QMessageBox::information(this,"提示","当前图像为最后一张!");
        return;
    }
    int idNext = id+1;
    getImageData(idNext);
    ui->le_id->setText(QString::number(idNext));
}

3.widget.ui
Please add a picture description

4. Download link

My example Baidu network disk link: https://pan.baidu.com/s/1RmVG4FQFI9NIe9T4clTRVQ
Extraction code: xxcj


Summarize

This article realizes the use of Sqlite database under Qt to save and read image data. The sql statement used in the demo implementation is relatively simple, but the actual project will be more complicated, so we still need to continue to learn to master more SQLite knowledge and skills.


hello:
Learn together and make progress together. If you still have related questions, you can leave a message in the comment area for discussion.

Guess you like

Origin blog.csdn.net/XCJandLL/article/details/131009962