How to store image in SQLite database

后端 未结 6 1839
一整个雨季
一整个雨季 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 03:07

    You have to use "blob" to store image.

    ex: to store a image in to db:

    public void insertImg(int id , Bitmap img ) {   
    
    
        byte[] data = getBitmapAsByteArray(img); // this is a function
    
        insertStatement_logo.bindLong(1, id);       
        insertStatement_logo.bindBlob(2, data);
    
        insertStatement_logo.executeInsert();
        insertStatement_logo.clearBindings() ;
    
    }
    
     public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, outputStream);       
        return outputStream.toByteArray();
    }
    

    To retrieve a image from db:

    public Bitmap getImage(int i){
    
        String qu = "select img  from table where feedid=" + i ;
        Cursor cur = db.rawQuery(qu, null);
    
        if (cur.moveToFirst()){
            byte[] imgByte = cur.getBlob(0);
            cur.close();
            return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
        }
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }       
    
        return null;
    } 
    

提交回复
热议问题