How to Store and Retrieve Image on SQLite

From Qt Wiki
Revision as of 15:47, 3 March 2015 by AutoSpider (talk | contribs) (Add "cleanup" tag)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

English | Deutsch | Español | Български

How to Store and Retrieve an Image or File with SQLite

Images or any files can be stored in a database. Here is one way to do it using the following steps:

1. Read the system file into a QByteArray. 2. Store QByteArray as a Binary Large Object in database.

For example :

 QFile file(fileName);
 if (!file.open(QIODevice::ReadOnly)) return;
 QByteArray byteArray = file.readAll();

QSqlQuery query;
 query.prepare("INSERT INTO imgtable (imgdata) VALUES (?)");
 query.addBindValue(byteArray);
 query.exec();

Now, the image/file can be retrieved like any other data

 QSqlQuery query("SELECT imgdata FROM imgtable");
 query.next();
 QByteArray array = query.value(0).toByteArray();

Creating a QPixmap from QByteArray :

 QPixmap pixmap = QPixmap();
 pixmap.loadFromData(array);

It is done. Now the pixmap can be used in a Button as icon or in label etc.