How to store an Image from Android to a SQlite and retrieve it?

By | December 23, 2012

Hello all…

In today’s post I will show you how to store an image in an SQLite database and retrieve it.

Image in SQLite DB

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”.

Make easy money with infolinks

Database Operations

DBHelper.java

package com.coderzheaven.storeimage;

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 " + 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 void Reset() {
        mDbHelper.onUpgrade(this.mDb, 1, 1);
    }

    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(true, IMAGES_TABLE, new String[]{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 com.coderzheaven.storeimage;

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();
    }

}

Make easy money with infolinks

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"?>
<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.coderzheaven.storeimage.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/imgView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/activity_horizontal_margin" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/btnSelectImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_menu_gallery" />

</android.support.design.widget.CoordinatorLayout>

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 com.coderzheaven.storeimage;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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 java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int SELECT_PICTURE = 100;
    private static final String TAG = "MainActivity";

    CoordinatorLayout coordinatorLayout;
    FloatingActionButton btnSelectImage;
    AppCompatImageView imgView;

    DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find the views...
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        btnSelectImage = (FloatingActionButton) findViewById(R.id.btnSelectImage);
        imgView = (AppCompatImageView) findViewById(R.id.imgView);

        btnSelectImage.setOnClickListener(this);

        // Create the Database helper object
        dbHelper = new DBHelper(this);

    }

    // Show simple message using SnackBar
    void showMessage(String message) {
        Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
        snackbar.show();
    }

    // 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) {

                Uri selectedImageUri = data.getData();

                if (null != selectedImageUri) {

                    // Saving to Database...
                    if (saveImageInDB(selectedImageUri)) {
                        showMessage("Image Saved in Database...");
                        imgView.setImageURI(selectedImageUri);
                    }

                    // Reading from Database after 3 seconds just to show the message
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (loadImageFromDB()) {
                                showMessage("Image Loaded from Database...");
                            }
                        }
                    }, 3000);
                }

            }
        }
    }

    @Override
    public void onClick(View v) {
        openImageChooser();
    }

    // Save the
    Boolean saveImageInDB(Uri selectedImageUri) {

        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;
        }

    }

    Boolean loadImageFromDB() {
        try {
            dbHelper.open();
            byte[] bytes = dbHelper.retreiveImageFromDB();
            dbHelper.close();
            // Show Image from DB in ImageView
            imgView.setImageBitmap(Utils.getImage(bytes));
            return true;
        } catch (Exception e) {
            Log.e(TAG, "<loadImageFromDB> Error : " + e.getLocalizedMessage());
            dbHelper.close();
            return false;
        }
    }
}

Build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.coderzheaven.storeimage"
        minSdkVersion 21
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
}

Source Code

You can download the complete Android Studio Source Code from here.

Send your comments to coderzheaven@gmail.com.

20 thoughts on “How to store an Image from Android to a SQlite and retrieve it?

  1. Chanchal

    Very nicely documented …
    can you please zip whole source code will help for android new bees 🙂

    Reply
    1. James Post author

      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.

      Reply
  2. Xavi

    how to retrive image from mysql server (databse )to android and display in it??

    Reply
    1. James Post author

      Create a image file in the server by reading from the mysql database and download the image.

      Reply
  3. Jannik Weiß

    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

    Reply
  4. Priyanka

    Please give the code for storage and retrieval of images in mysql

    Reply
    1. James Post author

      You can just store image in the SDCARD or the application sandbox and save the image path in the SQLite database.

      Reply
  5. Waheed

    Im facing errors in XML file
    android:src=”@drawable/ic_action_search”
    please make a quick reply Thanks

    Reply
    1. James Post author

      do u have “ic_action_search” image in your resources folder?

      Reply
  6. Jorge Prestige

    Deben crear una base de datos con cualquier manejador de achivos de sqlitemanager insertarla en sdcard0
    test.db and

    Reply
  7. George

    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)

    Reply
  8. Quang Minh

    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?

    Reply
    1. James Post author

      You will get the complete path of the image selected in onActivityResult function inside the activity.

      Reply
  9. Ivan

    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..

    Reply
    1. James Post author

      Its just a way to store an image in Database.

      Reply
  10. Aman

    It is Java.lang.NullPointerException at selectedimagepath..at this line..

    selectedImagePath = getPath(selectedImageUri);
    any suggestions how to correct it?

    Reply
  11. Brian

    Thank you for this wonderful tutorial. How can I be able to save more than one image?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *