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.
Very nicely documented …
can you please zip whole source code will help for android new bees 🙂
Sorry Chanchal.. I lost the sample code for this project. I created the post well that you just need to copy the post and it will work.
how to retrive image from mysql server (databse )to android and display in it??
Create a image file in the server by reading from the mysql database and download the image.
Hello,
the Programm works perfect until i press the “Store to Database” Button!
Then the error “Failed to open Database /storage/sdcard0/test.db” occures!
Can you help me? 🙂
Jannik
Please give the code for storage and retrieval of images in mysql
code is good but it produce error while save image and it can only save one image….
Nice ! There is any other way to store image by path. ?
You can just store image in the SDCARD or the application sandbox and save the image path in the SQLite database.
Im facing errors in XML file
android:src=”@drawable/ic_action_search”
please make a quick reply Thanks
do u have “ic_action_search” image in your resources folder?
Deben crear una base de datos con cualquier manejador de achivos de sqlitemanager insertarla en sdcard0
test.db and
Hi,
I am getting an error when I press save image in DB after getting image perfectly.
Below is my log
10-09 23:31:02.799: E/SQLiteLog(25806): (14) cannot open file at line 30192 of [00bb9c9ce4]
10-09 23:31:02.809: E/SQLiteLog(25806): (14) os_unix.c:30192: (2) open(/storage/emulated/0/test.db) –
10-09 23:31:02.869: E/SQLiteDatabase(25806): Failed to open database ‘/storage/emulated/0/test.db’.
10-09 23:31:02.869: E/SQLiteDatabase(25806): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
10-09 23:31:02.869: E/SQLiteDatabase(25806): at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
10-09 23:31:02.869: E/SQLiteDatabase(25806): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
10-09 23:31:02.869: E/SQLiteDatabase(25806): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
10-09 23:31:02.869: E/SQLiteDatabase(25806): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
10-09 23:31:02.869: E/SQLiteDatabase(25806): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
10-09 23:31:02.869: E/SQLiteDatabase(25806): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
10-09 23:31:02.869: E/SQLiteDatabase(25806): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
Hi,
I get this problem:
FileInputStream instream = new FileInputStream(selectedImagePath);
What’s selectedImagePath if my image is an ImageView? How to find out the path of this ImageView?
You will get the complete path of the image selected in onActivityResult function inside the activity.
Really really bad advice.. storing bytes of image in database..? this is super bad practise / antipattern.. Image path can be stored in database but actual image data should be saved as image separately..
Its just a way to store an image in Database.
It is Java.lang.NullPointerException at selectedimagepath..at this line..
selectedImagePath = getPath(selectedImageUri);
any suggestions how to correct it?
Well done with this wonderful example 🙂
Thank you for this wonderful tutorial. How can I be able to save more than one image?
Pingback: Kinh nghiệm là m Android – Trung's Note
this code is only for the select image from gallery and show in image view becoz in this tutorial Utils.class in this class getImage method not work so check properly
I will fix it. Thanks for the feedback.
Pingback: How to Uninstall Avast Anti Theft for Android? – CODERZHEAVEN