Search code examples
c#bitmapimage-manipulationbmp

Failure in writing a BMP file


I am trying to generate a BMP file that has some text. I created a winform application and I can succesfully create the BMP (I displayed it on a picture Box with no problems). However when I save it to a file, I just got a black image.

My code is

private void btnNameUsage_Click(object sender, EventArgs e)
{
   Bitmap bmp = new Bitmap(width, height);

   string name = "Hello how are you";
   string date = DateTime.Now.Date.ToString(); 

   Graphics thegraphics = Graphics.FromImage(bmp);

   string complete = date+"\n"+name ;

   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);
         }


   picBoxImage.Image = bmp;  //THIS WORKS

   //thegraphics.Flush();//I am not sure this is necessary and it changes nothing anyway

  bmp.Save(@"theImage.bmp",ImageFormat.Bmp);//I tried only one argument but it gave a png file. Now only a black BMP

   }

What am I doing wrong here?


Solution

  • The reason why PNG works and BMP doesn't is that PNG allows transparency in the image. In BMP the transparent parts of your image are rendered black (since it has to drop the alpha channel). Your text is also using a black brush, so you will get a black image.

    For on-screen rendering this is not an issue, since there, transparency is supported.