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


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 + " BLOB NOT NULL );";

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);

        public void onCreate(SQLiteDatabase db) {

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

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

    // 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));
            return blob;
        return null;

Image Utility Class


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


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"?>


            app:popupTheme="@style/AppTheme.PopupOverlay" />


        android:layout_margin="@dimen/activity_horizontal_margin" />

        android:src="@android:drawable/ic_menu_gallery" />


Activity Class


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;

    protected void onCreate(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

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


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

    // Choose an image from Gallery
    void openImageChooser() {
        Intent intent = new Intent();
        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...");

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


    public void onClick(View v) {

    // Save the
    Boolean saveImageInDB(Uri selectedImageUri) {

        try {
            InputStream iStream = getContentResolver().openInputStream(selectedImageUri);
            byte[] inputData = Utils.getBytes(iStream);
            return true;
        } catch (IOException ioe) {
            Log.e(TAG, "<saveImageInDB> Error : " + ioe.getLocalizedMessage());
            return false;


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


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.



  1. Chanchal February 12, 2013 at 11:50 am

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

    • James February 12, 2013 at 1:49 pm

      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.

  2. Xavi February 20, 2013 at 3:30 pm

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

    • James February 21, 2013 at 3:15 pm

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

  3. Jannik Weiß March 2, 2013 at 1:54 pm


    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? 🙂


  4. Priyanka March 10, 2013 at 7:17 pm

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

  5. sanket August 19, 2013 at 12:12 pm

    code is good but it produce error while save image and it can only save one image….

  6. hameed November 22, 2013 at 2:13 pm

    Nice ! There is any other way to store image by path. ?

    • James November 24, 2013 at 2:12 pm

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

  7. Waheed March 31, 2014 at 1:35 pm

    Im facing errors in XML file
    please make a quick reply Thanks

    • James April 3, 2014 at 5:24 pm

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

  8. Jorge Prestige April 9, 2014 at 2:44 pm

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

  9. George October 9, 2014 at 12:36 pm

    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)

  10. Quang Minh December 17, 2014 at 3:54 am

    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?

    • James December 19, 2014 at 5:48 pm

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

  11. Ivan July 7, 2015 at 12:14 pm

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

    • James July 8, 2015 at 8:48 am

      Its just a way to store an image in Database.

  12. Aman July 12, 2015 at 11:40 am

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

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

  13. Brian June 16, 2017 at 6:15 pm

    Well done with this wonderful example 🙂

  14. Brian June 22, 2017 at 5:57 am

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

  15. Pingback: Kinh nghiệm làm Android – Trung's Note

  16. MohammadAli January 29, 2018 at 8:01 am

    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

    • James February 18, 2018 at 12:43 am

      I will fix it. Thanks for the feedback.


Leave a Reply

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




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.