先前写过一个在PHP中往数据库中保存图像以及如何读取显示出来:
http://www.qtcn.org/blog/blog.php?do-showone-itemid-479-type-blog.html现在遇到了在Qt中把图像保存到数据库中(以BLOB类型保存)的问题,这里总结一下,供各位朋友参考
基本的思想和前面的使用PHP保存头像是一样的,这里以例子解说
1、加载一个头像到界面上显示出来(labelZhaoPian的大小是80x96)
显示头像,这里用QLabel来显示,代码如下:
extern QString g_strCurrentDir;
QString strImage = QFileDialog::getOpenFileName(this, "请选择照片文件", g_strCurrentDir, "图像文件 (*.png *.jpg *.bmp *.gif)");
if (strImage.isNull())
{
return;
}
g_strCurrentDir = QDir(strImage).absolutePath();
labelZhaoPian->setPixmap(QPixmap(strImage).scaled(labelZhaoPian->size()));
相应地,清除头像的代码就很简单了
labelZhaoPian->setPixmap(QPixmap());
labelZhaoPian->setText("照\n\n片");
2、保存图像到数据库中,以PNG格式
if (labelZhaoPian->pixmap()->isNull() == false)
{
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
labelZhaoPian->pixmap()->save(&buffer, "PNG");
QString out;
for(int n = 0; n < (int)bytes.size(); ++n)
{
QString str;
str.sprintf("%02x", (uchar)bytes[n]);
out.append(str);
}
query.exec(QString("UPDATE profile SET photo = 0x%1 WHERE ID = %2").arg(out).arg(iProfileId));
}
3、从数据库中读取出图像来,并显示
QSqlQuery q("SELECT photo FROM profile WHERE iprofileid = 1");
if (q.next())
{
if (q.isNull(0) == false)
{
QPixmap photo;
photo.loadFromData(q.value(0).toByteArray(), "PNG");
labelZhaoPian->setPixmap(photo);
}
}
[ 此贴被XChinux在2007-02-06 09:41重新编辑 ]