当前位置:Gxlcms > mysql > MySQL存入图片+Qt读入读出数据库中的图片_MySQL

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

时间:2021-07-01 10:21:17 帮助过:9人阅读

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

1.MySQL存入图片

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

  1. create table `sfood`(
  2. `name` varchar(255) not null,
  3. `type` varchar(255) not null,
  4. `material` varchar(255) not null,
  5. `price` int(200) not null,
  6. `feature` varchar(255) not null,
  7. `image` longblob,
  8. primary key(`name`)
  9. )ENGINE=innodb default charset=gb2312;

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为例:

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

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

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

人气教程排行