一、Bitmap转Drawable


Bitmap bm=xxx; //xxx根据你的情况获取

BitmapDrawable bd=new BitmapDrawable(bm);
因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。

二、 Drawable转Bitmap

转成Bitmap对象后,可以将Drawable对象通过Android的SK库存成一个字节输出流,最终还可以保存成为jpg和png的文件。
Drawable d=xxx; //xxx根据自己的情况获取drawable

BitmapDrawable bd = (BitmapDrawable) d;

Bitmap bm = bd.getBitmap();
最终bm就是我们需要的Bitmap对象了。



// 从资源中获取Bitmap
public static Bitmap getBitmapFromResources(Activity act, int resId) {
Resources res = act.getResources();
return BitmapFactory.decodeResource(res, resId);
}

// byte[] → Bitmap
public static Bitmap convertBytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}

// Bitmap → byte[]
public static byte[] convertBitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}

// 1)Drawable → Bitmap
public static Bitmap convertDrawable2BitmapByCanvas(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
// canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}

// 2)Drawable → Bitmap
public static Bitmap convertDrawable2BitmapSimple(Drawable drawable){
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}

// Bitmap → Drawable
public static Drawable convertBitmap2Drawable(Bitmap bitmap) {
BitmapDrawable bd = new BitmapDrawable(bitmap);
// 因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
return bd;
}

更多相关文章

  1. Android获取屏幕或View宽度和高度的方法
  2. Android(安卓)Retrofit的简单介绍和使用
  3. Android通过GPS或NetWork获取当前位置信息
  4. android 系统相应的服务
  5. Android(安卓)获取图库中图片的坑
  6. Android之微信开放平台创建应用
  7. Android(安卓)官方数据绑定 Data Binding Library
  8. Android(安卓)架构组件之 Lifecycle 使用详解
  9. Android(安卓)在低版本sdk中没有getSupportedPreviewFrameRates

随机推荐

  1. 【RS】H3C设备 配置SSH登录
  2. 【点宽专栏】Dual Thrust 交易策略
  3. 【点宽专栏】股票、期货量化投资策略系列
  4. 【点宽专栏】教你如何应用朴素贝叶斯分类
  5. 【点宽专栏】期货多因子(二)——各因子描述
  6. 【点宽专栏】验证Fama French五因子模型
  7. 【点宽专栏】国信证券——关于量化选股之
  8. 【点宽专栏】验证Fama French五因子模型
  9. 数字化转型的本质?——来自生物进化的启示
  10. 【点宽专栏】基于深度学习的股票涨跌预测