How to save bitmap in database?

前端 未结 4 1372
抹茶落季
抹茶落季 2021-02-02 02:46

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 \" +         


        
相关标签:
4条回答
  • 2021-02-02 03:14

    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);
    
    0 讨论(0)
  • 2021-02-02 03:25

    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 讨论(0)
  • 2021-02-02 03:30

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

    0 讨论(0)
  • 2021-02-02 03:33

    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

    0 讨论(0)
提交回复
热议问题