Android: save and retrieve image to SQLite database
Homan Huang
我是美国公民,SFSU大学毕业。专长是Kotlin, Java, C++程编,精通 Android 手机程式和后台支持软件--SpringBoot。电脑视觉:辨别物体,分辨算法。
Many people ask how to add the image to SQLite database. Actually, it is every easy.
Here is the process:
1. Get the source:
* Save images like JPEG, PNG, WEBP into drawable folder
Check official: https://developer.android.com/reference/android/graphics/Bitmap.CompressFormat.html
* Get it from capture.
2. Convert source to bitmap:
// MyData class holds image data
MyData mDataSample = new MyData();
...
// Source is route.png in drawable folder
Bitmap bitmap = ((BitmapDrawable) getDrawable(R.drawable.route)).getBitmap();
// Convert bitmap to byte[]. I create a function to do the work
mDataSample.setImageDataFromBitmap(bitmap);
For example, I have a class called MyData, which has function as setImageDataFromBitmap():
public class MyData {
private byte[] imageData = null;
...
// Bitmap to byte[] to imageData
public void setImageDataFromBitmap(Bitmap image) {
if (image != null) {
//bitmap to byte[]
imageData = bitmapToByte(image);
} else {
imageData = null;
}
}
// Bitmap to byte[]
public byte[] bitmapToByte(Bitmap bitmap) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bitmap to byte[] stream
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] x = stream.toByteArray();
//close stream to save memory
stream.close();
return x;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
...
3. Class MyData also converts byte[] to bitmap:
// Convert imageData directly to bitmap
public Bitmap getImageDataInBitmap() {
if (imageData != null) {
//turn byte[] to bitmap
return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
}
return null;
}
public byte[] getImageData() {
return imageData;
}
4. Deal with Database as usually:
* create database in YOUR ACTIVITY CLASS:
SQLiteDatabase db = this.openOrCreateDatabase(databaseName, MODE_PRIVATE, null);
* create table: save image data in BLOB
...
// Keyword I will use
private static final String KEY_IMAGE_DATA = "image_data";
private static final String KEY_RECORD_ID = "record_id";
...
//
String sql = "CREATE TABLE IF NOT EXISTS " + YOUR_TABLE_NAME + "(" +
... +
KEY_IMAGE_DATA + " BLOB, " +
KEY_RECORD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT )";
db.execSQL(sql);
5. Add record into database:
public void addRecord(... byte[] imageData ...) {
// Open database
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
...
// Column and value of column
values.put(KEY_IMAGE_DATA, imageData);
...
try {
newRecordId = db.insertOrThrow(RECORDS_TABLE, null, values);
} catch (SQLException e) {
Log.i(TAG, "ERROR: " + e.toString());
}
db.close();
}
6. Read record from database:
// Get data from mRecord_id
// MyData is a class hold my image data
public MyData getRecord(int mRecord_id) {
SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT * FROM " + RECORDS_TABLE
+ " WHERE " + KEY_RECORD_ID + " = " + String.valueOf(mRecord_id);
try {
Cursor cursor = db.rawQuery(sql, null);
MyData x = new MyData();
// Read data, I simplify cursor in one line
if (cursor != null) {
cursor.moveToFirst();
...
// Get imageData in byte[]. Easy, right?
x.setImageData( cursor.getBlob( cursor.getColumnIndex(KEY_IMAGE_DATA)) );
...
}
cursor.close();
db.close();
return x;
} catch (SQLException e) {
...
}
return null;
}
7. Put your data on screen.
ImageView testImageView = (ImageView) findViewById(R.id.testImageView);
...
// Get data from record table where record_id is 0
MyData testData = getRecord(0);
Bitmap testImage = testData.getImageDataInBitmap();
// Display sample bitmap in YOUR ImageView
testImageView.setImageBitmap(testImage);
The end.
Android Developer | Java | Kotlin | Firebase | SQLite Database | Android Studio | ViewModel | Figma | DSA
8 个月Output?
Full Stack Software Engineer @ Houzz | Java/NodeJS/JavaScript | US Healthcare
6 年Can you provide a way to capture and save image using Room architecture component?