Home Database Mysql Tutorial MySQL存入图片+Qt读入读出数据库中的图片_MySQL

MySQL存入图片+Qt读入读出数据库中的图片_MySQL

Jun 01, 2016 pm 01:01 PM
picture database

还记得之前的一个项目里要向数据库中存入图片,然后Qt要在数据库中读入读出图片,当时纠结了好久,查阅了很多资料才解决,所以希望本文能给需要朋友点帮助。好了废话不多说,下面开始讲实现步骤。

1.MySQL存入图片

首先建表时要声明字段的类型为longblob类型,如下:

create table `sfood`(
`name` varchar(255) not null,
`type` varchar(255) not null,
`material` varchar(255) not null,
`price` int(200) not null,
`feature` varchar(255) not null,
`image` longblob,
primary key(`name`)
)ENGINE=innodb default charset=gb2312;
Copy after login

image就是我的图片字段,声明为longblob类型,表示食物的图片。

然后往表中插入数据:

insert into sfood(name,type,material,price,feature,image) values('生水白菜','川菜','白菜,生水',8,'清淡',LOAD_FILE('G:\\images\\chuancai\\baicai.jpg'));

这里LOAD_FILE('G:\\images\\chuancai\\baicai.jpg')的作用就是往image字段写入图片,这里用的是绝对路径,表示你图片所在的位子。这是在windows下,如果是在Linux下,要把目录间隔改成//。

这样我们就已经在数据库里写入了图片了。

2.在Qt里如何把图片从数据库里面读出来,接下来的代码都是以上面的表sfood为例:

QString select = "select * from sfood";
Copy after login
query.exec(select);
Copy after login
if( query.next() )
Copy after login
{
Copy after login
	QLabel *PicLabel = new QLabel();
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
QPixmap photo;
Copy after login
    photo.loadFromData(query.value(5).toByteArray(), "JPG"); //从数据库中读出图片为二进制数据,图片格式为JPG,然后显示到QLabel里
Copy after login
    PicLabel->setPixmap(photo);
Copy after login
    PicLabel->setScaledContents(true);
Copy after login
}
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
3.通过Qt往数据库中写入图片
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
query.exec("select * from sfood where name='"+nameEdit->text()+"'"); //我这里本段代码是添加菜品,该句是查询是否有该菜,按名字查询
Copy after login
    if(query.next())
Copy after login
    {
Copy after login
        QMessageBox::information(this,tr("警告"),tr("该菜已在数据库存储了"));
Copy after login
        db.Close();
Copy after login
        return;
Copy after login
    }
Copy after login
    query.prepare("insert into sfood(name,type,material,price,feature,image) values(?,?,?,?,?,?)");
Copy after login
    query.addBindValue(nameEdit->text());
Copy after login
    query.addBindValue(typeEdit->text());
Copy after login
    query.addBindValue(materialEdit->toPlainText());
Copy after login
    query.addBindValue(priceEdit->text());
Copy after login
    query.addBindValue(featureEdit->text());
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
    //接下来代码是保存图片到数据库
Copy after login
    imagePath.replace("\\","/");  //转换路径格式,imagePath是图片文件的路径,我这里用的是绝对路径
Copy after login
    /*imagePath的获得方法可以这样写:
Copy after login
imagePath = QFileDialog::getOpenFileName(this, tr("Open File"),
Copy after login
                                                           "/home",
Copy after login
                                                          tr("Images (*.jpg)"));
Copy after login
    */
Copy after login
    
Copy after login
Copy after login
Copy after login
    QByteArray bytes;
Copy after login
    QBuffer buffer(&bytes);
Copy after login
    buffer.open(QIODevice::WriteOnly);
Copy after login
    pictureLabel->pixmap()->save(&buffer,"JPG");
Copy after login
    
Copy after login
Copy after login
Copy after login
    
Copy after login
Copy after login
Copy after login
    QByteArray data;
Copy after login
    QFile* file=new QFile(imagePath); //file为二进制数据文件名
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
    file->open(QIODevice::ReadOnly);
Copy after login
    data = file->readAll();
Copy after login
    file->close();
Copy after login
    QVariant var(data);
Copy after login
    query.addBindValue(var);
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
    query.exec();
Copy after login

ok,已经通过Qt将图片写入数据库了。

没什么技巧,希望可以帮到跟我一样需要的菜鸟,也期望有师兄指教错误或者是有更好的方法。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

PHP connections to different databases: MySQL, PostgreSQL, Oracle and more PHP connections to different databases: MySQL, PostgreSQL, Oracle and more Jun 01, 2024 pm 03:02 PM

PHP database connection guide: MySQL: Install the MySQLi extension and create a connection (servername, username, password, dbname). PostgreSQL: Install the PgSQL extension and create a connection (host, dbname, user, password). Oracle: Install the OracleOCI8 extension and create a connection (servername, username, password). Practical case: Obtain MySQL data, PostgreSQL query, OracleOCI8 update record.

How to handle database connections and operations using C++? How to handle database connections and operations using C++? Jun 01, 2024 pm 07:24 PM

Use the DataAccessObjects (DAO) library in C++ to connect and operate the database, including establishing database connections, executing SQL queries, inserting new records and updating existing records. The specific steps are: 1. Include necessary library statements; 2. Open the database file; 3. Create a Recordset object to execute SQL queries or manipulate data; 4. Traverse the results or update records according to specific needs.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

See all articles