由于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;
}