Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save bitmap in database?

Tags:

android

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.

like image 205
Monali Avatar asked Jun 14 '11 09:06

Monali


People also ask

How to store bitmap in database?

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

Can we save image in SQLite database?

Using this application you can get an image from a drawable folder and store it in an SQLite Database and also you can retrieve that image from the SQLite database to be shown on the screen. Use the following procedure to create the sample. Go to "File" and select "Android Application Project".


2 Answers

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);
like image 102
Punit Sachan Avatar answered Oct 03 '22 00:10

Punit Sachan


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

like image 33
DArkO Avatar answered Oct 03 '22 02:10

DArkO