PDA

View Full Version : Insert a image into a MySql BLOB database fiel - using Model/View



graciano
17th February 2010, 11:17
Hello all,
In the picture i send it is possible to manage a table containing 3 flields:



mysql> describe foto;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(45) | NO | | NULL | |
| image | blob | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)


4299
The load button allows me to load an image form disk into a QLabel.
Now, if i press the add button a key is generated for the id, the name comes from the opened filname and ... the question is:

How can i manage the data for the hidden column (image) if i want to insert the loaded image into that BLOB?

Thanks for any tips on this subject

Lykurg
17th February 2010, 12:21
QImage::bits() and QImage::loadFromData().

graciano
17th February 2010, 14:32
Some working code ...


void Dialog::beforeInsertFoto(QSqlRecord &record)
{
//prepare data dor id - generated key
record.setValue("id", generateId("foto"));

//prepare data for name - get it form the label in the ui
record.setValue("name", ui->fileNameLabel->text());

//prepare data for image - get it from the label in the ui
QImage currentImage = ui->foto->pixmap()->toImage();
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
currentImage.save(&buffer, "PNG");
record.setValue("image", bytes);
}

void Dialog::insertNewRecord()
{
int row = modeloFoto->rowCount();
modeloFoto->insertRow(row);
modeloFoto->submitAll();

}

void Dialog::getCurrentRecord()
{
//get image filename
QModelIndex index = vistaFoto->currentIndex();
ui->fileNameLabel->setText(modeloFoto->data(modeloFoto->index(index.row(), foto_name),0).toString());

//get image
QVariant currentImage = modeloFoto->data(modeloFoto->index(index.row(), foto_image),0);
QByteArray bytes = currentImage.toByteArray();
QImage image;
image.loadFromData(bytes);
ui->foto->setPixmap(QPixmap::fromImage(image));
}


I was stuck in this final lines and the loadFromData helped.
Now i can exchange png and other data between objects in the ui/my model and view / MySql database.
Just posting in case somebody needs this and for comments on optimizing this code.

Thanks