Skip to content

Instantly share code, notes, and snippets.

@thomasweng15
Created January 21, 2015 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasweng15/6e4ea6ada9f7d68ef8d7 to your computer and use it in GitHub Desktop.
Save thomasweng15/6e4ea6ada9f7d68ef8d7 to your computer and use it in GitHub Desktop.
two ways to copy a System.Drawing.Bitmap into a 1D rgb pixel array.
Bitmap bmpOrig = new Bitmap(@"C:\Users\Thomas\Desktop\picture.png");
Bitmap bmpResized = new Bitmap(bmpOrig, new System.Drawing.Size(640, 480));
Bitmap bmp = bmpResized.Clone(new Rectangle(0,0,bmpResized.Width,bmpResized.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
//byte[] bytes = new byte[bmp.Width * bmp.Height * 3];
//int index = 0;
//for (int i = 0; i < bmp.Height; i++)
//{
// for (int j = 0; j < bmp.Width; j++)
// {
// System.Drawing.Color color = bmp.GetPixel(j,i);
// bytes[index] = color.R;
// bytes[index + 1] = color.G;
// bytes[index + 2] = color.B;
// index += 3;
// }
//}
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
IntPtr ptr = bmpData.Scan0; // Get the address of the first line.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
bmp.UnlockBits(bmpData);
string result = String.Join(",", rgbValues);
System.IO.File.WriteAllText(@"C:\Users\Thomas\test2.csv", result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment