web-dev-qa-db-ja.com

byte []に​​描画可能

ImageViewにWebからの画像があります。それは非常に小さく(ファビコン)、SQLiteデータベースに保存したいと思います。 mImageView.getDrawable()からDrawableを取得できますが、次に何をすべきかわかりません。 AndroidのDrawableクラスを完全に理解していません。

次のようなBitmapからバイト配列を取得できることを知っています。

Bitmap defaultIcon = BitmapFactory.decodeStream(in);

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

byte[] bitmapdata = stream.toByteArray();

しかし、どのようにしてDrawableからバイト配列を取得できますか?

56
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();
132
Cristian

すべてに感謝し、これは私の問題を解決しました。

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();
18
Randula
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tester);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
5
Kalpesh

DrawableがBitmapDrawableの場合、これを試すことができます。

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

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

Bitmap.getRowBytes()は、ビットマップのピクセルの行間のバイト数を返します。

詳細については、このプロジェクトを参照してください: LazyList

0
Favas Kv