複製影像給3維陣列
1 public static byte[,,] GetRGBData(Bitmap bitImg) 2 { 3 int heigh = bitImg.Height; 4 int width = bitImg.Width; 5 6 Rectangle rect = new Rectangle(0, 0, width, heigh); 7 BitmapData bitmapData = bitImg.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); 8 IntPtr imgPtr = bitmapData.Scan0; 9 int stride = bitmapData.Stride; 10 int widthByte = width * 3; 11 int skipByte = stride - widthByte; 12 byte[,,] rgbData = new byte[width, heigh, 3]; 13 unsafe 14 { 15 byte* ptr = (byte*)(void*)imgPtr; 16 for (int x = 0; x < width; x++) 17 { 18 for (int y = 0; y < heigh; y++) 19 { 20 rgbData[x, y, 2] = ptr[0]; 21 rgbData[x, y, 1] = ptr[1]; 22 rgbData[x, y, 0] = ptr[2]; 23 ptr += 3; 24 } 25 ptr += skipByte; 26 } 27 } 28 bitImg.UnlockBits(bitmapData); 29 return rgbData; 30 }
將3維陣列變成影像
1 public static Bitmap SetRGB(byte[,,] rgbData) 2 { 3 Bitmap bitImg; 4 int width = rgbData.GetLength(0); 5 int heigh = rgbData.GetLength(1); 6 7 bitImg = new Bitmap(width, heigh, PixelFormat.Format24bppRgb); 8 Rectangle rect = new Rectangle(0, 0, width, heigh); 9 BitmapData bitmapData = bitImg.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); 10 IntPtr imgPtr = bitmapData.Scan0; 11 12 int stride = bitmapData.Stride; 13 int widthByte = width * 3; 14 int skipByte = stride - widthByte; 15 16 unsafe 17 { 18 byte* p = (byte*)(void*)imgPtr; 19 for (int x = 0; x < width; x++) 20 { 21 for (int y = 0; y < heigh; y++) 22 { 23 p[0] = (byte)rgbData[x, y, 2]; //p --> B 24 p[1] = (byte)rgbData[x, y, 1]; //p --> G 25 p[2] = (byte)rgbData[x, y, 0]; //p --> R 26 p+=3; 27 } 28 p += skipByte; 29 } 30 } 31 bitImg.UnlockBits(bitmapData); 32 33 return bitImg; 34 }