Store Image in Sqlite Database in Android
Hello all…
In today's post I will show you how to store an image in an SQLite database and retrieve it.
First I will just create a Database Helper Class for adding and reading from the Database.
Our Database contains only one table "Images" with two columns "id" and "image".
Note : If you want to see the SQLite DB Structure and values in Eclipse you can check this post.
We are going to save our selected image in the column "image".
Database Operations
DBHelper.java
package store_image_in_sqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper { public static final String IMAGE_ID = "id"; public static final String IMAGE = "image"; private final Context mContext; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "Images.db"; private static final int DATABASE_VERSION = 1; private static final String IMAGES_TABLE = "ImagesTable"; private static final String CREATE_IMAGES_TABLE = "CREATE TABLE IF NOT EXISTS " + IMAGES_TABLE + " (" + IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + IMAGE + " BLOB NOT NULL );"; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_IMAGES_TABLE); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //db.execSQL("DROP TABLE IF EXISTS " + CREATE_IMAGES_TABLE); onCreate(db); } } public DBHelper(Context ctx) { mContext = ctx; mDbHelper = new DatabaseHelper(mContext); } public DBHelper open() throws SQLException { mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } // Insert the image to the Sqlite DB public void insertImage(byte[] imageBytes) { ContentValues cv = new ContentValues(); cv.put(IMAGE, imageBytes); mDb.insert(IMAGES_TABLE, null, cv); } // Get the image from SQLite DB // We will just get the last image we just saved for convenience... public byte[] retreiveImageFromDB() { Cursor cur = mDb.query(false, IMAGES_TABLE, new String[]{IMAGE_ID, IMAGE}, null, null, null, null, IMAGE_ID + " DESC", "1"); if (cur.moveToFirst()) { byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE)); cur.close(); return blob; } cur.close(); return null; } }
Image Utility Class
Utils.java
package store_image_in_sqlite; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class Utils { public static byte[] getImageBytes(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); return stream.toByteArray(); } public static Bitmap getImage(byte[] image) { return BitmapFactory.decodeByteArray(image, 0, image.length); } public static byte[] getBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } return byteBuffer.toByteArray(); } }
Layout
Our layout mainly contains a Floating button, for selecting an image and
an ImageView for showing the image Selected and Image from the Database.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/coordinatorLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:fitsSystemWindows="true" android:gravity="center_horizontal" android:orientation="vertical" android:padding="10dp" tools:context="store_image_in_sqlite.StoreImageActivity"> <Button android:id="@+id/btnSelectImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginBottom="5dp" android:text="Select Image" /> <android.support.v7.widget.AppCompatImageView android:id="@+id/imgView" android:layout_width="100dp" android:layout_height="100dp" android:layout_below="@+id/btnSelectImage" android:layout_marginBottom="5dp" /> <Button android:id="@+id/btnSaveImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/imgView" android:layout_marginBottom="5dp" android:text="Save Image in DB" /> <Button android:id="@+id/btnLoadImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/btnSaveImage" android:layout_marginBottom="5dp" android:text="Load Image in DB" /> <android.support.v7.widget.AppCompatImageView android:id="@+id/loadedImg" android:layout_width="100dp" android:layout_height="100dp" android:layout_below="@+id/btnLoadImage" android:layout_marginBottom="5dp" /> <TextView android:id="@+id/tvStatus" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/loadedImg" android:layout_marginBottom="5dp" android:gravity="center" android:text="Select an image and save in DB" android:textSize="20sp" /> </RelativeLayout>
Activity Class
MainActivity.java
On Selecting the image, we will insert it into the database, show a message to the user and after 3 seconds, we will read it back from the database.
package store_image_in_sqlite; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatImageView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.IOException; import java.io.InputStream; import tutorials.coderzheaven.com.androidtutorialprojects.R; public class StoreImageActivity extends AppCompatActivity implements View.OnClickListener { private static final int SELECT_PICTURE = 100; private static final String TAG = "StoreImageActivity"; private Button btnOpenGallery, btnSaveImage, btnLoadImage; private TextView tvStatus; private AppCompatImageView imgView, imgLoaded; private Uri selectedImageUri; private DBHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.store_image_activity); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Find the views... btnOpenGallery = findViewById(R.id.btnSelectImage); btnSaveImage = findViewById(R.id.btnSaveImage); btnLoadImage = findViewById(R.id.btnLoadImage); imgLoaded = findViewById(R.id.loadedImg); imgView = findViewById(R.id.imgView); tvStatus = findViewById(R.id.tvStatus); btnOpenGallery.setOnClickListener(this); btnSaveImage.setOnClickListener(this); btnLoadImage.setOnClickListener(this); // Create the Database helper object dbHelper = new DBHelper(this); } void showMessage(final String message) { tvStatus.post(new Runnable() { @Override public void run() { tvStatus.setText(message); } }); } // Choose an image from Gallery void openImageChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { selectedImageUri = data.getData(); if (null != selectedImageUri) { imgView.setImageURI(selectedImageUri); } } } } @Override public void onClick(View v) { if (v == btnOpenGallery) openImageChooser(); if (v == btnSaveImage) { // Saving to Database... if (saveImageInDB()) { showMessage("Image Saved in Database..."); } } if (v == btnLoadImage) loadImageFromDB(); } boolean saveImageInDB() { try { dbHelper.open(); InputStream iStream = getContentResolver().openInputStream(selectedImageUri); byte[] inputData = Utils.getBytes(iStream); dbHelper.insertImage(inputData); dbHelper.close(); return true; } catch (IOException ioe) { Log.e(TAG, "<saveImageInDB> Error : " + ioe.getLocalizedMessage()); dbHelper.close(); return false; } } void loadImageFromDB() { new Thread(new Runnable() { @Override public void run() { try { dbHelper.open(); final byte[] bytes = dbHelper.retreiveImageFromDB(); dbHelper.close(); // Show Image from DB in ImageView imgLoaded.post(new Runnable() { @Override public void run() { imgLoaded.setImageBitmap(Utils.getImage(bytes)); showMessage("Image Loaded from Database"); } }); } catch (Exception e) { Log.e(TAG, "<loadImageFromDB> Error : " + e.getLocalizedMessage()); dbHelper.close(); } } }).start(); } }
Source Code
You can download the complete Android Studio Source Code from here.
Note: Please note that you cannot save bigger images in Sqlite Database. ndroid SQLite returns rows in cursor windows that have the maximum size of 2MB as specified by config_cursorWindowSize. If your row exceeds this limit, you'll get error. If you want to save bigger image, then save the path of the image.
Send your comments to coderzheaven@gmail.com.
Store Image in Sqlite Database in Android
Source: https://www.coderzheaven.com/2012/12/23/store-image-android-sqlite-retrieve-it/
0 Response to "Store Image in Sqlite Database in Android"
Post a Comment