Android 中 Bitmap 和 Drawable 相互转换的方法

文章转自:http://blog.csdn.net/l_lhc/article/details/50923372

一、Drawable 转换成 Bitmap

方法一

通过 BitmapFactory 中的 decodeResource 方法,将资源文件中的 R.drawable.ic_drawable 转化成Bitmap

Resources res = getResources();
Bitmap    bmp = BitmapFactory.decodeResource(res, R.drawable.ic_drawable);

方法二

将 Drable 对象先转化成 BitmapDrawable ,然后调用 getBitmap 方法 获取

Resource res      = gerResource();
Drawable drawable = res.getDrawable(R.drawable.ic_drawable);//获取drawable
BitmapDrawable bd = (BitmapDrawable) drawable;
Bitmap bm         = bd.getBitmap();

方法三

根据已有的Drawable创建一个新的Bitmap

public static Bitmap drawableToBitmap(Drawable drawable) {

    int w = drawable.getIntrinsicWidth();
    int h = drawable.getIntrinsicHeight();
    System.out.println("Drawable转Bitmap");
    Bitmap.Config config =
            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                    : Bitmap.Config.RGB_565;
    Bitmap bitmap = Bitmap.createBitmap(w, h, config);
    //注意,下面三行代码要用到,否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, w, h);
    drawable.draw(canvas);

    return bitmap;
}

二、Bitmap 转换成 Drawable

使用 BitmapDrawable 对 Bitmap 进行强制转换

Drawable drawable = new BitmapDrawable(bmp);

三、Bitmap 转换成 byte[]

public static byte[] getBytes(Bitmap bitmap){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

    return baos.toByteArray();
 }

四、byte[] 转化成 Bitmap

public static Bitmap Bytes2Bimap(byte[] b) {
    if (b.length != 0) {
        return BitmapFactory.decodeByteArray(b, 0, b.length);
    } else {
        return null;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值