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.
I tried quite a lot to acomplish that. First what I have:
var resources = new ComponentResourceManager(typeof(Game));
var bmp = (Bitmap)(resources.GetObject("imgBall.Image"));
the only so far not giving me an error message (but displaying the picutre wrong) is this:
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();
then I tried solutions I could find in stack overflow already:
ImageConverter imgConverter = new ImageConverter();
pixelData = (System.Byte[])imgConverter.ConvertTo(bmp, Type.GetType("System.Byte[]"));
This changes the size of pixelData, so that I cannot use it anymore...
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);
}
here at the CopyPixels line I am confused: when I take rawStride
from above (84) I get an error message it needs to be at lease 112. When I calculate stride for bitmapImage
(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.
I have the feeling that I understand something completely wrong here.