通过纯RGB数据流生成Bitmap对象


   

升级  41.75%

98

主题

286

帖子

2万

e币

No.6 江湖开发者

Rank: 6Rank: 6

积分
3502
跳转到指定楼层
楼主
回复 
  发表于 2011-4-12 23:06:29  |  只看该作者  | 只看大图  回帖奖励
0
本帖最后由 geniuseoe2011 于 2013-5-8 09:22 编辑

GOOGLE对于图像的读取处理,已经封装了Bitmap类和BitmapFactory类,可以说囊括了许多种读取图片数据的方式,但是如果我们只有纯RGB数据(byte[])和位图宽和高又如何将数据上屏显示呢?
查看SDK文档,虽然没有关于byte[]数组的构建BITMAP对象的API
但是有[url=file:///C:/Program%20Files/android-sdk-windows/docs/reference/android/graphics/Bitmap.html#createBitmap(int[], int, int, android.graphics.Bitmap.Config)]createBitmap[/url](int[] colors, int width, int height, Bitmap.Config config) 这个方法
于是就有了思路,就是将byte[]数组转化为int[]数组,以下是本人封装的一个类用以实现通过byte[]数据流构建BITMAP的对象:
public class MyBitmap{

static public Bitmap createMyBitmap(byte[] data, int width, int height){ 
  int []colors = convertByteToColor(data);
  if (colors == null){
   return null;
  }
   
  Bitmap bmp = Bitmap.createBitmap(colors, 0, width, width, height, 
           Bitmap.Config.ARGB_8888);      
  return bmp;
}


// 将一个byte数转成int
// 实现这个函数的目的是为了将byte数当成无符号的变量去转化成int
public static int convertByteToInt(byte data){
  
  int heightBit = (int) ((data>>4) & 0x0F);
  int lowBit = (int) (0x0F & data);
  return heightBit * 16 + lowBit;
}


// 将纯RGB数据数组转化成int像素数组
public static int[] convertByteToColor(byte[] data){
  int size = data.length;
  if (size == 0){
   return null;
  }
  
  int arg = 0;
  if (size % 3 != 0){
   arg = 1;
  }
  
  // 一般情况下data数组的长度应该是3的倍数,这里做个兼容,多余的RGB数据用黑色0XFF000000填充  
  int []color = new int[size / 3 + arg];
  int red, green, blue;
  
  if (arg == 0){
   for(int i = 0; i < color.length; ++i){
    red = convertByteToInt(data[i * 3]);
    green = convertByteToInt(data[i * 3 + 1]);
    blue = convertByteToInt(data[i * 3 + 2]); 
    
    // 获取RGB分量值通过按位或生成int的像素值      
    color = (red << 16) | (green << 8) | blue | 0xFF000000; 
   }
  }else{
   for(int i = 0; i < color.length - 1; ++i){
    red = convertByteToInt(data[i * 3]);
    green = convertByteToInt(data[i * 3 + 1]);
    blue = convertByteToInt(data[i * 3 + 2]); 
    color = (red << 16) | (green << 8) | blue | 0xFF000000; 
   }
   
   color[color.length - 1] = 0xFF000000;
  }

  return color;
}
}

以下是测试效果图:
 
第一张是直接加载资源里的图片显示
第二张提取图片的RGB数据,然后通过上述类构建BITMAP对象后贴图
下面附上工程文件,有什么不明白的大家踊跃提问哈{:4_84:}
或者有更好的思路可以提出来,大家交流一下哈
 TestBitampAny.rar (52.95 KB, 下载次数: 313) 

welcome to join android develop communicate group:298044305 
温馨提示:
代码里有个地方错了
   color[color.length] = 0xFF000000;改为  color[color.length - 1] = 0xFF000000;
不然代码要是跑进来会出现数组越界异常的。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值