If it is better to save the image in a Datatype Blob, or in a file with the route as a reference in the table depends on the size of your images.
You can find a table that indicates how large a square can be saved directly in the table at this page As you can see, up to a size of 20k it is always possible to save the direct Blob, with larger sizes that depends on the page size in the access to SQLite.
The versions of SQLite used on Android are currently all earlier than 3.12 , meaning that the default page size is 1024 bytes.
To change the page size you can use PRAGMA
, before to create the table :
PRAGMA page_size = 4096;
(The Pragma
can for example add in onCreate
of your SQLiteOpenHelper
)
The procedure to save images from Bitmap
would be:
- compress the bitmap by
ByteArrayOutputStream
- write the
byte[]
of the stream as blob in your table:
- a
CREATE TABLE imagenes (id INTEGER PRIMARY KEY, img BLOB);
table is assumed with a SQLiteOpenHelper helper
In code:
public void guardarImagen(long id, Bitmap bitmap){
// tamaño del baos depende del tamaño de tus imagenes en promedio
ByteArrayOutputStream baos = new ByteArrayOutputStream(20480);
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , baos);
byte[] blob = baos.toByteArray();
// aqui tenemos el byte[] con el imagen comprimido, ahora lo guardemos en SQLite
SQLiteDatabase db = helper.getWritableDatabase();
String sql = "INSERT INTO imagenes (id, img) VALUES(?,?)";
SQLiteStatement insert = db.compileStatement(sql);
insert.clearBindings();
insert.bindLong(1, id));
insert.bindBlob(2, blob);
insert.executeInsert();
db.close();
}
To recover an image according to id
you can use:
public Bitmap buscarImagen(long id){
SQLiteDatabase db = helper.getReadableDatabase();
String sql = String.format("SELECT * FROM imagenes WHERE id = %d", id);
Cursor cursor = db.rawQuery(sql, new String[] {});
Bitmap bitmap = null;
if(cursor.moveToFirst()){
byte[] blob = cursor.getBlob(1);
ByteArrayInputStream bais = new ByteArrayInputStream(blob);
bitmap = BitmapFactory.decodeStream(bais);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
db.close();
return bitmap;
}