使用指针把图片转换成二维数组
1/// <summary>
2 /// 使用指针扫描图片,返回存放像素值的二维数组(高,宽)
3 /// </summary>
4 /// <param name="bmp">预处理图片</param>
5 /// <param name="grizzly">是否为灰色图片</param>
6 /// <returns>返回存放像素值的二维数组(高,宽)</returns>
7 public string[,] LeveScan(Bitmap bmp, bool grizzly)
8 {
9 //创建图像 (防止LockBits方法出错,多加了一步)
10 Bitmap bmNew = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format24bppRgb);
11 Graphics g = Graphics.FromImage(bmNew);
12 g.DrawImage(bmp, new Point(0, 0));
13 g.Dispose();
14 string[,] temp = new string[bmp.Height, bmp.Width];
15 //获取图像的BitmapData对像
16 BitmapData data = bmNew.LockBits(new Rectangle(0, 0, bmNew.Width, bmNew.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
17 //循环处理
18 unsafe
19 {
20 byte* ptr = (byte*)(data.Scan0);
21 for (int i = 0; i < data.Height; i++)
22 {
23 for (int j = 0; j < data.Width; j++)
24 {
25 if (grizzly)
26 {
27 temp[i, j] = ptr[2].ToString(); //红
28 }
29 else
30 {
31 temp[i, j] = ptr[2].ToString() + "-"; //红
32 temp[i, j] += ptr[1].ToString() + "-"; //绿
33 temp[i, j] += ptr[0].ToString(); //蓝
34 }
35 ptr += 3;
36 }
37 ptr += data.Stride - data.Width * 3;
38 }
39 }
40 bmNew.UnlockBits(data);
41 return temp;
42 }