Created
August 18, 2017 20:02
-
-
Save Tarelochkin/ab123baa2676570257214cbf14a321c4 to your computer and use it in GitHub Desktop.
Save and retrieve an image to/from a database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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