Android 可绘制到字节[]

Android 可绘制到字节[],android,database,drawable,android-bitmap,Android,Database,Drawable,Android Bitmap,我在ImageView中有一张来自web的图像。它非常小(favicon),我想将它存储在我的SQLite数据库中。 我可以从mImageView.getDrawable()获得一个Drawable,但是我不知道接下来该怎么做。我不完全理解Android中的Drawable类 我知道我可以从位图中获取字节数组,如: Bitmap defaultIcon = BitmapFactory.decodeStream(in); ByteArrayOutputStream stream = new By

我在
ImageView
中有一张来自web的图像。它非常小(favicon),我想将它存储在我的SQLite数据库中。 我可以从
mImageView.getDrawable()
获得一个
Drawable
,但是我不知道接下来该怎么做。我不完全理解Android中的
Drawable

我知道我可以从
位图中获取字节数组,如:

Bitmap defaultIcon = BitmapFactory.decodeStream(in);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);

byte[] bitmapdata = stream.toByteArray();
但是如何从
可绘制的
中获取字节数组呢

Drawable d; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();

现在图像存储在bytearray中。

谢谢大家,这解决了我的问题

Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.my_pic);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();

如果Drawable是BitmapDrawable,您可以试试这个

long getSizeInBytes(Drawable drawable) {
    if (drawable == null)
        return 0;

    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
    return bitmap.getRowBytes() * bitmap.getHeight();
}
位图.getRowBytes()返回位图像素中行与行之间的字节数


有关更多信息,请参阅此项目:

感谢您的关注!!没有考虑过强制转换它。它应该是:bitmap.compress(bitmap.CompressFormat.JPEG,100,stream);否则该流不包含任何数据…@Cristian我将bitmapdata作为BLOB保存在数据库中,当我再次从BLOB恢复可绘制时,背景变为黑色。你能帮我吗?我希望背景像保存到数据库之前一样透明。@Hissain因为JPG不存储透明度,所以需要PNG。注意:在大多数情况下,用90(而不是100)压缩JPEG是最好的方法!此帖子被自动标记为低质量,因为它只是代码。您是否介意通过添加一些文本来扩展它,以解释它是如何解决问题的?我将bitMapData作为BLOB保存在数据库中,当我再次从BLOB恢复可绘制时,背景变为黑色。你能帮我吗?我希望背景像保存到数据库之前一样透明。我认为这是一个与此过程并行的不同问题。如果您可以提供更多细节以进行复制和检查,那就太好了。在使用JPEG格式保存时发生了这种情况,但我将其改为PNG,效果很好……这是一个更好的答案,因为它不需要强制转换为BitmapDrawable,而drawable实际上可能不是它的一个实例。@mattsnider谢谢
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tester);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
long getSizeInBytes(Drawable drawable) {
    if (drawable == null)
        return 0;

    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
    return bitmap.getRowBytes() * bitmap.getHeight();
}