android 可绘制到byte[]

9bfwbjaz  于 2022-12-25  发布在  Android
关注(0)|答案(6)|浏览(213)

我在ImageView中有一个来自网络的图像。它非常小(一个favicon),我想将它存储在我的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中获取字节数组呢?

uqxowvwt

uqxowvwt1#

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();
p4rjhz4m

p4rjhz4m2#

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

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();
hlswsv35

hlswsv353#

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tester);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
tyu7yeag

tyu7yeag4#

如果Drawable是BitmapDrawable,则可以尝试此选项。

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

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

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

欲了解更多,请参阅此项目:LazyList

k5ifujac

k5ifujac5#

这是我的Utility函数,可以复制粘贴

/**
 * @param ctx the context
 * @param res the resource id
 * @return the byte[] data of the fiven drawable identified with the resId
 */
public static byte[] getDrawableFromRes(Context ctx, @DrawableRes int res) {
    Bitmap bitmap = BitmapFactory.decodeResource(ctx.getResources(), res);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    return stream.toByteArray();
}
jk9hmnmh

jk9hmnmh6#

File myFile = new File(selectedImagePath);

byte [] mybytearray  = new byte [filelenghth];

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

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

现在图像被存储在字节数组中。

相关问题