android在处理一写图片资源的时候,会进行一些类型的转换,现在有空整理一下:

1、Drawable → Bitmap

Java代码

1. public static Bitmap drawableToBitmap(Drawable drawable) {
2.
3. Bitmap bitmap = Bitmap
4. .createBitmap(
5. drawable.getIntrinsicWidth(),
6. drawable.getIntrinsicHeight(),
7. drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
8. : Bitmap.Config.RGB_565);
9. Canvas canvas = new Canvas(bitmap);
10. //canvas.setBitmap(bitmap);
11. drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
12. drawable.draw(canvas);
13. return bitmap;
14. }

public static Bitmap drawableToBitmap(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、从资源中获取Bitmap

Java代码

1. Resources res=getResources();
2.
3. Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);

Resources res=getResources();

Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);

3、Bitmap → byte[]

Java代码

1. private byte[] Bitmap2Bytes(Bitmap bm){
2. ByteArrayOutputStream baos = new ByteArrayOutputStream();
3. bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
4. return baos.toByteArray();
5. }

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

4、 byte[] → Bitmap

Java代码

1. private Bitmap Bytes2Bimap(byte[] b){
2. if(b.length!=0){
3. return BitmapFactory.decodeByteArray(b, 0, b.length);
4. }
5. else {
6. return null;
7. }
8. }

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

以上是我在实践中遇到的一些转换,以后遇到类似的就不用到处找了,希望对大家也有一点用处!

更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
  3. 一款霸榜 GitHub 的开源 Linux 资源监视器!
  4. android相机拍照
  5. eclipse下如何关联android-support-v4.jar源码
  6. Android(安卓)Matrix源码详解
  7. android中使用多个CheckBox联动,CheckBox的setOnCheckedChangeLis
  8. android 二维码 扫描与生成(内置)
  9. Android使double保留两位小数的多方法 java保留两位小数

随机推荐

  1. 如何将所有插入调用标识到表中
  2. 将Excel表格多个Sheet表的数据转换为SQL
  3. SQL注入另类技巧
  4. 世界国家 的数据库sql
  5. mysql下载+安装+启动过程及问题解决
  6. Recordset记录集对象的属性
  7. SQL - 仅选择distinct一列
  8. Excel 复制Sql查询结果错位
  9. 新手求助一条sql语句~~帮忙看看
  10. SQL 日志太大,脚本清除