title: System.Drawing.Bitmap to Byte Array
body: <p>I have a Bitmap from a resource and need to put it in a byte array. I have a SetPixel Methode for manipulating pixels in my Byte Array. That works all well. What I want to do, is to load first a picture in the array that I can manipulate it later. </p>
  
  <p>I tried quite a lot to acomplish that. First what I have:</p>
  
  <pre><code>var resources = new ComponentResourceManager(typeof(Game));
  var bmp = (Bitmap)(resources.GetObject("imgBall.Image"));
  </code></pre>
  
  <p>the only so far not giving me an error message (but displaying the picutre wrong) is this:</p>
  
  <pre><code>width = (int)bmp.Width;
  height = (int)bmp.Height;
  System.Windows.Media.PixelFormat pf = PixelFormats.Rgb24;
  rawStride = (width * pf.BitsPerPixel + 7) / 8;
  byte[] pixelData = new byte[rawStride * height];    
  
  MemoryStream ms = new MemoryStream();
  bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
  pixelData = ms.GetBuffer();
  </code></pre>
  
  <p>then I tried solutions I could find in stack overflow already:</p>
  
  <pre><code>ImageConverter imgConverter = new ImageConverter();
  pixelData = (System.Byte[])imgConverter.ConvertTo(bmp, Type.GetType("System.Byte[]"));
  </code></pre>
  
  <p>This changes the size of pixelData, so that I cannot use it anymore...</p>
  
  <pre><code>using (MemoryStream memory = new MemoryStream())
              {
                  bmp.Save(memory, ImageFormat.Bmp);
                  memory.Position = 0;
                  var bitmapImage = new BitmapImage();
                  bitmapImage.BeginInit();
                  memory.Seek(0, SeekOrigin.Begin);
                  bitmapImage.StreamSource = memory;
                  bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                  bitmapImage.EndInit();
                  int stride = width * ((bitmapImage.Format.BitsPerPixel + 7) / 8);                                
  
                  bitmapImage.CopyPixels(pixelData, stride, 0);                
              }
  </code></pre>
  
  <p>here at the CopyPixels line I am confused: when I take <code>rawStride</code> from above (84) I get an error message it needs to be at lease 112. When I calculate stride for <code>bitmapImage</code> (112) it complains it needs to be minimum 3136. I even tried to enter the number of stride manually it compains allways it needs to be bigger.</p>
  
  <p>I have the feeling that I understand something completely wrong here.</p>