BGR转Bitmap

/*
     * byte[] data保存的是纯RGB的数据,而非完整的图片文件数据
     */
    static public Bitmap createMyBitmap(byte[] data, int width, int height){
        int []colors = convertByteToColor(data);
        if (colors == null){
            return null;
        }
        Bitmap bmp = null;

        try {
            bmp = Bitmap.createBitmap(colors, 0, width, width, height,
                    Bitmap.Config.ARGB_8888);
        } catch (Exception e) {
            // TODO: handle exception

            return null;
        }

        return bmp;
    }


    /*
     * 将RGB数组转化为像素数组
     */
    private static int[] convertByteToColor(byte[] data){
        int size = data.length;
        if (size == 0){
            return null;
        }


        // 理论上data的长度应该是3的倍数,这里做个兼容
        int arg = 0;
        if (size % 3 != 0){
            arg = 1;
        }

        int []color = new int[size / 3 + arg];
        int red, green, blue;


        if (arg == 0){                                  //  正好是3的倍数
            for(int i = 0; i < color.length; ++i){

                color[i] = (data[i * 3] << 16 & 0x00FF0000) |
                        (data[i * 3 + 1] << 8 & 0x0000FF00 ) |
                        (data[i * 3 + 2] & 0x000000FF ) |
                        0xFF000000;
            }
        }else{                                      // 不是3的倍数
            for(int i = 0; i < color.length - 1; ++i){
                color[i] = (data[i * 3] << 16 & 0x00FF0000) |
                        (data[i * 3 + 1] << 8 & 0x0000FF00 ) |
                        (data[i * 3 + 2] & 0x000000FF ) |
                        0xFF000000;
            }

            color[color.length - 1] = 0xFF000000;                   // 最后一个像素用黑色填充
        }

        return color;
    }

方法二

 /*
     * byte[] data保存的是纯RGB的数据,而非完整的图片文件数据
     */
    static public Bitmap createMyBitmap(byte[] data, int width, int height) {
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        int row = height - 1, col = width-1;
        for (int i = data.length-1; i >= 3; i -= 3) {
            int color = data[i-2] & 0xFF;
            color += (data[i-1] << 8) & 0xFF00;
            color += ((data[i]) << 16) & 0xFF0000;
            bmp.setPixel(col--, row, color);
            if (col < 0) {
                col = width-1;
                row--;
            }
        }
        return bmp;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值