PDA

View Full Version : best way to load image from db



C167
4th April 2008, 14:46
Hi, i'm currently loading images from a sqlite3 blob-field using this code:
void ImageViewer::loadImage ( int pic )
{
QSqlQuery query ( QSqlDatabase::database() );
query.prepare ( "SELECT data FROM img_images WHERE id = :id" );
query.bindValue ( ":id", img_list[pic] );
query.exec();
if ( query.next() )
{
return QImage::fromData ( query.value ( 0 ).toByteArray() ) );
}
else
{
return QImage();
}
}Now i found some examples in one of my Qt-Books:
QImage ImageCollection::getImage( int id )
{
QSqlQuery qrx;
qry.prepare ( "SELECT data FROM images WHERE id = :id" );
qry.bindValue ( ":id", id );
if ( !qry.exec() ) qFatal ( "Failed to get image" );
if ( !qry.next() ) qFatal ( "Failed to get image id" );
QByteArray array = qry.value ( 0 ).toByteArray();
QBuffer buffer ( &array );
buffer.open ( QIODevice::ReadOnly );
QImageReader reader ( &buffer, "PNG" );
QImage image = reader.read();
return image;
}Which code is better, if i know that i only have one image format in the database and why? which one is the fastest?
Using Qt4.4b1, 4.4rc1 is compiling atm. System is Debian Sid.
C167

jacek
10th April 2008, 16:17
IMO the first version is better, because it's shorter and supports all possible images formats. It might be a bit slower, because Qt must detect the format, but I don't think you will notice the difference.

Lykurg
10th April 2008, 18:24
Hi,

because of QImage::fromData is defined as
QImage QImage::fromData(const uchar *data, int size, const char *format)
{
QByteArray a = QByteArray::fromRawData(reinterpret_cast<const char *>(data), size);
QBuffer b;
b.setData(a);
b.open(QIODevice::ReadOnly);
return QImageReader(&b, format).read();
}
both are equal. But as jacek mentioned your code is shorter in "front end", so I would prefer it.

If you need speed improvement store all images in the database in the same image format, and specify it in fromRawData(). Also if img_list is an private member and you definitely know the content you may use
query.exec( "SELECT data FROM img_images WHERE id = " + QString::number(img_list[pic]));
(assuming img_list[pic] will return an integer)

Lykurg