将Drawable转换为BLOB数据类型

时间:2011-06-14 10:06:34

标签: java android sqlite

public Drawable icon; \\ Some value in this field

我正在SQLite Manager中创建一个数据库。我想将icon存储到数据库中。另一个字段显示正确,但是当我使用数据类型为icon的{​​{1}}字段时,它不会显示。

BLOB

3 个答案:

答案 0 :(得分:14)

您可以将图像转换为字节数组,并将该bytearray存储在数据库中的blob中。您可以将数据作为字节数组从数据库中检索回来。

如何从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();

将字节数组存储在数据库中:

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

从字节数组中检索图像:

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

答案 1 :(得分:0)

我在上面的答案中做了一些改变来获取字节数组imageview

ImageView iv =(ImageView)findViewById(R.id.splashImageView);

iv.setDrawingCacheEnabled(true);
        Bitmap bitmap = iv.getDrawingCache();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] bitmapdata = stream.toByteArray();

答案 2 :(得分:0)

如果要将多个图像保存到数据库,则可以创建自己的方法,如下所示: //从drawable中检索图像到int数组:

int[] IMAGES = { R.drawable.yourimage1, R.drawable.yourimage2, R.drawable.yourimage3,
            R.drawable.yourimage4, R.drawable.yourimage5 }; 

//create method to convert drawable images(which are in int) to byte[] as below:

public byte[] convertToByteArray(int image){

        Resources resources = getResources();
        Drawable drawable = resources.getDrawable(image);
        Bitmap bitmap =  ((BitmapDrawable)drawable).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress( Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapData = stream.toByteArray();

              return bitmapData;

    }

现在调用此方法如下:                byte [] image = convertToByteArray(IMAGES [position]); //                dbAdapter.insertValues(图像);