以下是测试代码和验证结果:
static void Main( params string[] args )
{
Bitmap img = new Bitmap( @"E:\tempfolder\testimage.bmp" ); // 导入一张RGB彩色图片
Rectangle lockRect = new Rectangle( 0, 0, img.Width, img.Height );
BitmapData imgData = img.LockBits( lockRect, ImageLockMode.ReadOnly, img.PixelFormat );
byte[,] rband = new byte[ img.Height, img.Width ]; // 彩色图片的R、G、B三层分别构造一个二维数组
byte[,] gband = new byte[ img.Height, img.Width ];
byte[,] bband = new byte[ img.Height, img.Width ];
int rowOffset = imgData.Stride - img.Width * 3;
// 这里不用img.GetPixel方法,而采用效率更高的指针来获取图像像素点的值
unsafe
{
byte* imgPtr = ( byte* )imgData.Scan0.ToPointer();
for( int i = 0; i < img.Height; ++i )
{
for( int j = 0; j < img.Width; ++j )
{
rband[ i, j ] = imgPtr[ 2 ]; // 每个像素的指针是按BGR的顺序存储的
gband[ i, j ] = imgPtr[ 1 ];
bband[ i, j ] = imgPtr[ 0 ];
imgPtr += 3; // 偏移一个像素
}
imgPtr += rowOffset; // 偏移到下一行
}
}
img.UnlockBits( imgData );
}
