网上发现C#将图片转换层RGB32的byte的结果很少,找了很多代码,经过自己的多次调试,终于实现了。具体代码片段如下:
/// <summary>
/// Bitmap转换层RGB32
/// </summary>
/// <param name="Source">Bitmap图片</param>
/// <returns></returns>
public static byte[] GetRgb32_From_Bitmap(Bitmap Source)
{
bool bError = false;
string errorMsg = string.Empty;
return GetRgb32_From_Bitmap(Source, ref bError, ref errorMsg);
}
/// <summary>
/// Bitmap转换层RGB32
/// </summary>
/// <param name="Source">Bitmap图片</param>
/// <returns></returns>
public static byte[] GetRgb32_From_Bitmap(Bitmap Source, ref bool bError, ref string errorMsg)
{
bError = false;
int lPicWidth = Source.Width;
int lPicHeight = Source.Height;
Rectangle rect = new Rectangle(0, 0, lPicWidth, lPicHeight);
System.Drawing.Imaging.BitmapData bmpData = Source.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, Source.PixelFormat);
IntPtr iPtr = bmpData.Scan0;
int picSize = lPicWidth * lPicHeight * 4;
byte[] pRrgaByte = new byte[picSize];
System.Runtime.InteropServices.Marshal.Copy(iPtr, pRrgaByte, 0, picSize);
Source.UnlockBits(bmpData);
int iPoint = 0;
int A = 0;
try
{
//for (int iRow = 0; iRow < lPicHeight; iRow++)
//{
// for (int jCol = 0; jCol < lPicWidth; jCol++)
// {
// pRrgaByte[4 * (iRow * lPicWidth + jCol) + 0] = Convert.ToByte(pRrgaByte[iPoint++]);
// pRrgaByte[4 * (iRow * lPicWidth + jCol) + 1] = Convert.ToByte(pRrgaByte[iPoint++]);
// pRrgaByte[4 * (iRow * lPicWidth + jCol) + 2] = Convert.ToByte(pRrgaByte[iPoint++]);
// pRrgaByte[4 * (iRow * lPicWidth + jCol) + 3] = Convert.ToByte(A);
// }
//}
bError = true;
errorMsg = "BMP数据转换成功";
return pRrgaByte;
}
catch (Exception exp)
{
pRrgaByte = null;
bError = false;
errorMsg = exp.ToString();
//throw;
}
return null;
}