There seem to be many picturebox questions out there, but I haven't found any that deal with changing the contents of a picturebox to a bitmap that was not simply loaded from file.
My application takes an array of bytes and generates a bitmap from them. I really want to avoid writing to a file as an intermediate processing step.
Because it is an array of bytes, and not 2-byte words, I needed to make an indexed bitmap with a grayscale palette.
I then converted the indexed bitmap to a normal one (24 bit rgb).
This is the code that is causing an error for me:
pictureBox1.Image = (System.Drawing.Image)bmp2;
When I view the form (the picturebox tries to draw), the thread will simply halt execution with a message: "invalid parameter at System.Drawing.Image.get_RawFormat()"
What am I doing wrong? How can I create a safe bitmap for the picturebox?
This is what creates "bmp2":
//creating the bitmap from the array
System.Drawing.Bitmap bmp1 = new System.Drawing.Bitmap(100, 100, 100, System.Drawing.Imaging.PixelFormat.Format8bppIndexed, MyIntPtr);
//creating a proper indexed palette
System.Drawing.Imaging.ColorPalette GrayPalette = bmp1.Palette;
for (int i = 0; i < GrayPalette.Entries.Length; i++)
{
GrayPalette.Entries[i] = Color.FromArgb(i, i, i);
}
bmp1.Palette = GrayPalette;
//creating a non-indexed, 24bppRGB bitmap for picturebox compatibility
System.Drawing.Bitmap bmp2 = new Bitmap(bmp1.Width, bmp1.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Graphics gr = Graphics.FromImage(bmp2);
gr.DrawImage(bmp1, 0, 0);
gr.Dispose();
If I use bmp1.Save(@"testfile.bmp") I get a perfectly acceptable bitmap that appears to be without anomaly.
Why can't I use my bitmap as my picturebox.Image? Are there additional parameters of the picturebox I need to change prior to loading the new bitmap into it?