Android中Bitmap、Drawable、byte[]互转

Bitmap -> Drawable

Drawable drawable = new BitmapDrawable(bmp);

Drawable -> Bitmap

//Drawable资源
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.sample);

//Drawable对象
public Bitmap drawable2Bitmap(Drawable drawable) {
    Config config;
    if (drawable.getOpacity() != PixelFormat.OPAQUE) {
        config = Bitmap.Config.ARGB_8888;
    } else {
        config = Bitmap.Config.RGB_565;
    }
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight(), config);
    Canvas canvas = new Canvas(bitmap);
    // canvas.setBitmap(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                             drawable.getIntrinsicHeight());
    drawable.draw(canvas);
    return bitmap;
}

Bitmap -> byte[]

private byte[] bitmap2Bytes(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
}

byte[] -> Bitmap

private Bitmap bytes2Bitmap(byte[] bytes) {
    if (bytes.length != 0) {
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    } else {
        return null;
    }
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/11/android-bitmap-drawable-bytes-conversion/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Android中Bitmap、Drawable、byte[]互转
Bitmap -> Drawable Drawable drawable = new BitmapDrawable(bmp); Drawable -> Bitmap //Drawable资源 Bitmap bmp = BitmapFactory.decodeResource(r……
<<上一篇
下一篇>>
文章目录
关闭
目 录