Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u014746838/article/details/88577495
The first method is first inserted into the column in the database: alter table student add image mediumblob;
Here with mediumblob, represents storage medium-size image.
Memory function
QPixmap image("xxx");
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
QVariant imageData(bytes);
QSqlQuery query;
query.prepare("insert into studen (Sno, Sname, Ssex, Scome, classNo, image)"
query.bindValue(0, 1);
...
query.bindValue(5, imageData);
query.exec();
Read function
query.exec("select * student");
while (query.next())
{
QPixmap p;
p.loadFromData(query.value(5).toByteArray(), "PNG");
//Do some thing...
}
The second method for accessing the picture is actually very simple, but the need to use when reading loadFromData QPixmap like the picture is loaded, the second parameter to specify the format of the picture, "jpg" / "png" if corresponding to not correct, it loads the image does not come out, therefore, desirable to increase the field types of data stored in the database
1. Picture of deposit:
//插入图片
QByteArray data;
QFile* file=new QFile("D:\\test.jpg"); //fileName为二进制数据文件名
file->open(QIODevice::ReadOnly);
data = file->readAll();
file->close();
QVariant var(data);
query.bindValue(":picture" , var);
2. read the picture
QPixmap photo;
photo.loadFromData(query.value(3).toByteArray(), query.value(4).toString().toLatin1());
//用label将图片进行加载
ui->label->setPixmap(photo);
3.ini的与图片存入类似
4.ini的读取,PS:这里需要注意要设置让写入的代码支持中文,不然中文就会乱码或者显示问号
QFile file("D:\\test.ini");
file.open(QIODevice::ReadWrite | QIODevice::Truncate);
file.resize(0);
QTextStream in(&file);
QByteArray array = query.value(3).toByteArray();
QTextCodec* gbk_codec = QTextCodec::codecForName("GBK");
QString gbk_string = gbk_codec->toUnicode(array);
in << gbk_string;