How to store and retrieve a byte array (image data) to and from a SQLite database?
21,736
Byte array can be stored as BLOB data type. There's nothing special in this procedure except special care for chunking, like:
InputStream is = context.getResources().open(R.drawable.MyImageFile);
try {
byte[] buffer = new byte[CHUNK_SIZE];
int size = CHUNK_SIZE;
while(size == CHUNK_SIZE) {
size = is.read(buffer); //read chunks from file
if (size == -1) break;
ContentValues cv = new ContentValues();
cv.put(CHUNK, buffer); //CHUNK blob type field of your table
long rawId = database.insert(TABLE, null, cv); //TABLE table name
}
} catch (Exception e) {
Log.e(TAG, "Error saving raw image to: "+rawId, e);
}
Author by
Alex
Updated on July 19, 2022Comments
-
Alex almost 2 years
How do I store and retrieve a byte array (image data) to and from a SQLite database in Android?
-
SadeepDarshana almost 8 years@gevorg why is chunking needed?
-
SadeepDarshana almost 8 years@barmaley Are the chunks all appended into a single blob in a single record (that is do you get one final blob containing the whole image) or are multiple records created per chunk? (as in this code)
-
gevorg almost 8 years@SadeepDarshana answer is not mine, I just corrected the code formatting.