Monali
Monali

Reputation: 1966

How to save bitmap in database?

I want to know how to save a bitmap in database. I created table in db as:

@Override
public void onCreate(SQLiteDatabase db)
{
    db.execSQL("CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,image BLOB)");         
}    

My problem is I am not able to insert the image. Please tell me in which format I need to insert the image.

Upvotes: 11

Views: 27954

Answers (4)

Punit Sachan
Punit Sachan

Reputation: 593

If you have Bitmap image then you can do following.

Bitmap photo = <Your image>
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();

Then you can save data in table using following way.

db = YourDBHelper.getInstance(ctx).getWritableDatabase();    
ContentValues values = new ContentValues();         
values.put("image", bArray);            
db.insert(TABLE_NAME , null, values);

Upvotes: 16

Karthik
Karthik

Reputation: 391

Try this one

InputStream is = mycon.getAssets().open("data/Images/img1");
                if (is.available() == -1) {
                    Log.v(null, "Images not read to Input stream");
                }
                if (is != null) {
                    BufferedInputStream bis = new BufferedInputStream(is, 128);
                    ByteArrayBuffer barb = new ByteArrayBuffer(128);
                    // read the bytes one by one and append it into the
                    // ByteArrayBuffer barb
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                        barb.append((byte) current);
                    }
                    values.put("imageData", barb.toByteArray());

Upvotes: 0

DArkO
DArkO

Reputation: 16110

if you want to do that you need to use a blob. but why do you have to do this.. i wouldn't store images into a database. its better to store the image on the sdcard and then store its path into the database. often databases are installed on the phone memory and that will just fill the phone memory up...

Upvotes: 10

Related Questions