How to Store and Retrieve Image on SQLite/es

From Qt Wiki
Jump to navigation Jump to search
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.

Español English

Como Guardar y Recuperar una Imagen o Archivo con SQLite

Imágenes o cualquier tipo de archivos pueden ser guardados en un banco de datos. Aguí esta una manera de hacerlo siguiendo los siguientes pasos:

1. Cargar el archivo dentro de un QByteArray. 2. Guardar el QByteArray como un Binary Large Object (BLOB) en el banco de datos.

Por ejemplo :

 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();

Ahora, la imagen/archivo puede ser recuperada como cualquier otro tipo de dato

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

Creando un QPixmap desde un QByteArray :

 QPixmap pixmap;
 pixmap.loadFromData(array);

Esta hecho. Ahora el pixmap puede ser usado en un QButton como un icono o en un QLabel, etc.