Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

How to Store and Retrieve Image on SQLite: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Cleanup)
(various minor fixes)
Line 1: Line 1:
{{LangSwitch}}
{{LangSwitch}}
[[Category:snippets]]
 
[[Category:HowTo]]
Images or any files can be stored in a database. Here is one way to do it using the following steps:
Images or any files can be stored in a database. Here is one way to do it using the following steps:


Line 7: Line 6:
# Store QByteArray as a Binary Large Object in database.
# Store QByteArray as a Binary Large Object in database.


For example :
For example:


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


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


Now, the image/file can be retrieved like any other data
Now, the image/file can be retrieved like any other data
<code>
<code>
QSqlQuery query("SELECT imgdata FROM imgtable");
QSqlQuery query("SELECT imgdata FROM imgtable");
query.next();
query.next();
QByteArray array = query.value(0).toByteArray();
QByteArray array = query.value(0).toByteArray();
</code>
</code>


Line 33: Line 32:
</code>
</code>


It is done. Now the pixmap can be used in a Button as icon or in label etc.
It is done. Now the pixmap can be used in a {{class|QPushButton}} as icon or in label etc.
 
[[Category:Snippets]]
[[Category:HowTo]]

Revision as of 15:34, 16 November 2015

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

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 QPushButton as icon or in label etc.