前面只实现了8,24位转8位byte数组。
这里实现32位bitmap转8位byte数组,代码如下:
public byte[] bmp2byteArr(Bitmap org_Bitmap)//返回8位byteArr
{
//原图针对8位和24位和32位bitmap
Rectangle rc = new Rectangle(0, 0, org_Bitmap.Width, org_Bitmap.Height);
System.Drawing.Imaging.BitmapData bmpdata = org_Bitmap.LockBits(rc,
System.Drawing.Imaging.ImageLockMode.ReadWrite,
org_Bitmap.PixelFormat);
IntPtr imageptr = bmpdata.Scan0;
int ww = org_Bitmap.Width;
int hh = org_Bitmap.Height;
int bytes = 0;
if (org_Bitmap.PixelFormat == PixelFormat.Format32bppArgb)
{
bytes = ww * hh * 4;//此处针对的是32位位图
}
if (org_Bitmap.PixelFormat == PixelFormat.Format24bppRgb)
{
bytes = ww * hh * 3;//此处针对的是24位位图
}
if (org_Bitmap.PixelFormat == PixelFormat.Format8bppIndexed)
{
bytes = ww * hh;
}
byte[] glob_rgbOrGrey = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(imageptr, glob_rgbOrGrey, 0, bytes);
org_Bitmap.UnlockBits(bmpdata);
byte[] grey8 = new byte[ww * hh];
if (org_Bitmap.PixelFormat == PixelFormat.Format24bppRgb)
{
for (int i = 0; i < ww; i++)
for (int j = 0; j < hh; j++)
{
int m = j * ww + i;
grey8[m] = glob_rgbOrGrey[3 * m];
}
return grey8;
}else
if (org_Bitmap.PixelFormat == PixelFormat.Format32bppArgb)
{
for (int i = 0; i < ww; i++)
for (int j = 0; j < hh; j++)
{
int m = j * ww + i;
grey8[m] = glob_rgbOrGrey[4 * m];
}
return grey8;
}
else
{
return glob_rgbOrGrey;
}
}
做个备份,方便查找使用。