I have successfully generated a BMP file. (I am still tweaking some changes in format I am required to do though). I created a winform with a PictureBox. Following my last question, I now can save the file, but now the bitmap cannot be displayed in the PictureBox. This happened after I changed the palette following this answer to have the alpha of the colors set to 0
My bmp is monochrome as taught in this answer (I wonder whether there could be a simpler way)
My code is
private void btnNameUsage_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(width, height);
// Bitmap bmp = new Bitmap(width, height, PixelFormat.Format1bppIndexed); //This does not work
bmp.SetResolution(300.0F, 300.0F);
string name = "Hello how are you";
string date = DateTime.Now.Date.ToString();
using (Graphics thegraphics = Graphics.FromImage(bmp))
{
string complete = date + "\n" + name ;
thegraphics.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
using (Font font1 = new Font("Arial", 24, FontStyle.Regular, GraphicsUnit.Pixel))
using (var sf = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center,
})
{
thegraphics.DrawString(complete, font1, Brushes.Black, new Rectangle(0, 0, bmp.Width, bmp.Height), sf);
}
}
//add
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
Bitmap newBitmap = new Bitmap(width, height, bmpData.Stride, PixelFormat.Format1bppIndexed, bmpData.Scan0);
newBitmap.SetResolution(300.0F, 300.0F);
//we modify the palette THIS MAKES THE BMP NOT SHOWN IN PIT BOX
ColorPalette palette = newBitmap.Palette;
palette.Entries[0] = black; //black is a type Color
palette.Entries[1] = white; //white is a type Color
newBitmap.Palette = palette;
picBoxImage.Image = newBitmap; //THIS fails
newBitmap.Save(@"theImage.bmp", ImageFormat.Bmp); //This works!
}
I have to clarify that the generated pallete by default colors are (RGBA) black:000000FF and white: FFFFFFFF (with this palette I can see the bmp in the picbox) but I am changing to black :00000000 and white: FFFFFF00 (as you can see only the A component is changed)
the variables black and white are
Color black = new Color();
Color white = new Color();
white = Color.FromArgb(0, 255, 255, 255); //the 0 is alpha zero
black = Color.FromArgb(0, 0, 0, 0); //the first 0 is alpha zero
I wonder why it is not showing.
As a side question, how can I change the "number of important colors" in the DIB header?
EDIT: I experimented with the alpha setting (for example 128) and I could see the picture only slightly less bright colors.(as in grey) This only happens when displaying the bmp. The saved file is correctly black and white
What is the relation between picturebox and alpha...