How to store image in SQLite database

后端 未结 6 1714
一整个雨季
一整个雨季 2020-11-22 02:38

In my application I am uploading an image from gallery and I want to store this image in the SQLite database. How do I store a bitmap in the database? I am converting bitmap

6条回答
  •  遇见更好的自我
    2020-11-22 02:51

    Use blob to store your image in your sqlite database. Below is an example on how to to use blob.

    Setting Up the database

    CREATE TABLE " + DB_TABLE + "("+ 
                       KEY_NAME + " TEXT," + 
                       KEY_IMAGE + " BLOB);";
    

    Insert in the Database:

    public void addEntry( String name, byte[] image) throws SQLiteException{
        ContentValues cv = new  ContentValues();
        cv.put(KEY_NAME,    name);
        cv.put(KEY_IMAGE,   image);
        database.insert( DB_TABLE, null, cv );
    }
    

    Retrieving data:

     byte[] image = cursor.getBlob(1);
    

    Note:

    1. Before inserting into database, you need to convert your Bitmap image into byte array first then apply it using database query.
    2. When retrieving from database, you certainly have a byte array of image, what you need to do is to convert byte array back to original image. So, you have to make use of BitmapFactory to decode.

    Below is an Utility class which I hope could help you:

    public class DbBitmapUtility {
    
        // convert from bitmap to byte array
        public static byte[] getBytes(Bitmap bitmap) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 0, stream);
            return stream.toByteArray();
        }
    
        // convert from byte array to bitmap
        public static Bitmap getImage(byte[] image) {
            return BitmapFactory.decodeByteArray(image, 0, image.length);
        }
    }
    

提交回复
热议问题