60

我有一张来自网络的图片ImageView。它非常小(一个图标),我想将它存储在我的 SQLite 数据库中。我可以从中得到一个DrawablemImageView.getDrawable()但我不知道下一步该做什么。我不完全了解DrawableAndroid中的课程。

我知道我可以从类似的地方得到一个字节数组Bitmap

Bitmap defaultIcon = BitmapFactory.decodeStream(in);

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

byte[] bitmapdata = stream.toByteArray();

但是如何从 a 中获取字节数组Drawable

4

5 回答 5

142
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();
于 2010-12-14T04:19:09.383 回答
22

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

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();
于 2012-04-01T18:03:13.977 回答
7
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tester);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
于 2012-07-16T10:05:16.363 回答
0

如果 Drawable 是 BitmapDrawable 你可以试试这个。

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

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

Bitmap.getRowBytes()返回位图像素中行之间的字节数。

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

于 2014-06-13T14:36:57.973 回答
-2
File myFile = new File(selectedImagePath);

byte [] mybytearray  = new byte [filelenghth];

BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(myFile));

bis1.read(mybytearray,0,mybytearray.length);

现在图像存储在字节数组中..

于 2010-12-14T06:09:51.480 回答