Convert Drawable to BLOB Datatype

后端 未结 3 1265
执念已碎
执念已碎 2020-12-06 03:32
public Drawable icon; \\\\ Some value in this field

I am creating a database in SQLite Manager. I want to store icon into the database

3条回答
  •  清歌不尽
    2020-12-06 04:13

    You can convert your image into byte array and store that bytearray in blob filed in database. You can retrieve your image back from database as byte array.

    How to get byte array from imageview:

    ImageView iv = (ImageView) findViewById(R.id.splashImageView);
    Drawable d = iv.getBackground();
    BitmapDrawable bitDw = ((BitmapDrawable) d);
    Bitmap bitmap = bitDw.getBitmap();
    System.out.println(".....d....."+d);
    System.out.println("...bitDw...."+bitDw);
    System.out.println("....bitmap...."+bitmap);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] imageInByte = stream.toByteArray();
    

    Store byte array in database:

    ContentValues cv = new ContentValues();
    cv.put(CHUNK, buffer); //CHUNK blob type field of your table
    long rawId = database.insert(TABLE, null, cv); //TABLE table name
    

    Retrieve image from byte array:

    public static Bitmap convertByteArrayToBitmap(
        byte[] byteArrayToBeCOnvertedIntoBitMap)
    {
        bitMapImage = BitmapFactory.decodeByteArray(
            byteArrayToBeCOnvertedIntoBitMap, 0,
            byteArrayToBeCOnvertedIntoBitMap.length);
        return bitMapImage;
    }
    

提交回复
热议问题