Skip to content

Instantly share code, notes, and snippets.

@Tarelochkin
Created August 18, 2017 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tarelochkin/ab123baa2676570257214cbf14a321c4 to your computer and use it in GitHub Desktop.
Save Tarelochkin/ab123baa2676570257214cbf14a321c4 to your computer and use it in GitHub Desktop.
Save and retrieve an image to/from a database
// save to db
private void saveItem() {
ContentValues values = new ContentValues();
values.put(InventoryEntry.COLUMN_IMAGE, BitmapUtility.bitmapToBlob(mBitmap));
}
// retrieve from db (via CursorLoader)
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
int imageIndex = cursor.getColumnIndex(InventoryEntry.COLUMN_IMAGE);
byte[] imageBlob = cursor.getBlob(imageIndex);
if (imageBlob != null && imageBlob.length > 0 && !flagBitmapSet) {
mBitmap = BitmapUtility.blobToBitmap(imageBlob);
//TODO: display image
}
}
// convert from bitmap to byte array
private byte[] bitmapToBlob(Bitmap bitmap) {
byte[] byteStream = new byte[0];
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byteStream = stream.toByteArray();
stream.close();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
return byteStream;
}
}
// convert from byte array to bitmap
private Bitmap blobToBitmap(byte[] bytes) {
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment