简体   繁体   中英

C# Graphics shown in Form but not in Bitmap

I'm using C# and I would like to draw some polygons on a Form, then to save the graphics in a Bitmap.

Following this question answers I wrote a method in my Form class:

  private void draw_pol()
  {
      Graphics d = this.CreateGraphics();

      // drawing stuff

      Bitmap bmp = new Bitmap(this.Width, this.Height, d);
      bmp.Save("image.bmp");
  }

In this way the Form displays correctly the graphics and the Bitmap file named "image.bmp" is created, but that file is a white image.

Why isn't the bmp file showing any image? What I'm doing wrong?

Thank you very much.

The graphics parameter you are passing to your bitmap is only used to specify the resolution of the bitmap. It does not in any way paint to the bitmap.

from MSDN :

The new Bitmap that this method creates takes its horizontal and vertical resolution from the DpiX and DpiY properties of g, respectively.

Instead, use Graphics.FromImage() to get a Graphics object you can use. Moreover, you should Dispose the Graphics object after painting. This is an ideal usage for the using statement.

Bitmap bmp = new Bitmap(this.Width, this.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
    //paint stuff
}
bmp.Save(yourFile);

If you also need to paint this to the form, you can easily just draw the bitmap you created:

Graphics g = this.CreateGraphics();
g.DrawImage(bmp, 0, 0);

A Graphics instance only operates on one Bitmap . It's either the one you want to save, or the one on your form.

You can for example do this to render the drawn bitmap on your form and save it afterwards:

private void DrawOnBitmap()
{
    using (var bitmap = new Bitmap(this.Width, this.Height))
    {
        using (var bitmapGraphics = Graphics.FromImage(bitmap))
        {
            // Draw on the bitmap
            var pen = new Pen(Color.Red);
            var rect = new Rectangle(20, 20, 100, 100);
            bitmapGraphics.DrawRectangle(pen, rect);

            // Display the bitmap on the form
            using (var formGraphics = this.CreateGraphics())
            {
                formGraphics.DrawImage(bitmap, new Point(0, 0));
            }

            // Save the bitmap
            bitmap.Save("image.bmp");
        }
    }
}   

you need a graphics object that represents the bitmap,so that you can draw on image.do lke this:

  • create the bitmap object
  • create the graphics object using Graphics.FromImage method
  • pass bitmap object as argument to graphics object

     Bitmap bmp = new Bitmap(this.Width, this.Height, d); bmp.Save("image.bmp");//for your need Graphics d=Graphics.FromImage(bmp); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM