第一种方法,首先在数据库中插入列:alter table student add image mediumblob;
这里用mediumblob,表示存储中等大小的图片。
存储函数
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();
读取函数
query.exec("select * student");
while (query.next())
{
QPixmap p;
p.loadFromData(query.value(5).toByteArray(), "PNG");
//Do some thing...
}
第二种方法,对于图片的存取其实很简单,但是在读取的时候需要用到QPixmap类的loadFromData对图片进行加载,第二个参数需要指定图片的格式,“jpg"/"png"如果对应不正确的话,图片就加载不出来,因此,最好在数据库中增加一个字段存储数据类型
1.图片的存入:
//插入图片
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.图片的读取
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;
这篇博客介绍了两种在Qt中将图片存储到MySQL数据库的方法。第一种方法是在数据库中添加mediumblob类型的列,然后使用特定的存储和读取函数。第二种方法涉及QPixmap的loadFromData来加载图片,并需要在数据库中额外存储图片格式信息,以确保正确读取。
1352

被折叠的 条评论
为什么被折叠?



