开发者

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 i开发者_运维知识库nsert the image.


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


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


Write it to binary and store as a BLOB... You are on the right track. You can also do it with objects.

http://www.idevelopment.info/data/Programming/java/jdbc/LOBS/BLOBFileExample.java

Dont forget Google code too:

http://www.google.de/search?sourceid=chrome&ie=UTF-8&q=java+write+to+binary+and+store+in+BLOB#hl=de&safe=off&sa=X&ei=9y_3TbzLBcOZOobyqagK&ved=0CBgQBSgA&q=google+code+java+write+to+binary+and+stored+in+BLOB&spell=1&bav=on.2,or.r_gc.r_pw.&fp=562730531e5070d5&biw=1440&bih=787


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜