Unity 读取1-bit bmp图片文件

由于unity本身不支持直接从文件中去读取bmp,如果不应用System.Drawing去读取bmp文件是分厂麻烦的事情。由于项目原因,不能引入这个dll,又要读取这样1-bit的黑白色的二维码图片,所以只能自己去逐像素读取这种1-bit格式的bmp图片,然后赋值给Textre2d。留个笔记

			 BitmapFileHeader bfh;
            BitmapInfoHeader bih;
            BMP.readbmpheader(bytes, out bfh, out bih);///获取bmp文件头的信息,现主要只用了宽高
 
 			UnityEngine.Color[] colors = new Color[bih.biWidth* bih.biHeight];
            int counter = 0;//行像素计数
            int index = 0;
            int rowCount = (bih.biWidth + 7) / 8;//行字节数
            int rowOffset = 0;//行对齐最接偏移数
            if (rowCount % 4!=0)
            {
                rowOffset = 4 - rowCount % 4;
            } 
            for (int j = (int)bfh.bfOffsetBits; j < bytes.Length; j++)
            {
                for (int i = 7; i >= 0; i--)
                {
                    colors[index] = GetBitValue(bytes[j], i)==1?Color.white : Color.black;//获取颜色
                    index++;
                    counter++;
                    if (counter == bih.biWidth)
                    {
                        j += rowOffset;
                        counter = 0;
                        break;///一行扫描完毕
                    }
                }
            }

		private static int GetBitValue(byte b, int index)
        {
            switch (index)
            {
                case 0: return (b & 1) == 1 ? 0 : 1;
                case 1: return (b & 2) == 2 ? 0 : 1;
                case 2: return (b & 4) == 4 ? 0 : 1;
                case 3: return (b & 8) == 8 ? 0 : 1;
                case 4: return (b & 16) == 16 ? 0 : 1;
                case 5: return (b & 32) == 32 ? 0 : 1;
                case 6: return (b & 64) == 64 ? 0 : 1;
                case 7: return (b & 128) == 128 ? 0 : 1;
            }
            return 0;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值