Saving System.Drawing.Graphics to a png or bmp

前端 未结 5 960
不思量自难忘°
不思量自难忘° 2020-12-08 20:15

I have a Graphics object that I\'ve drawn on the screen and I need to save it to a png or bmp file. Graphics doesn\'t seem to support that directly, but it must be possible

5条回答
  •  情话喂你
    2020-12-08 21:10

    Here is the code:

    Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    Graphics g = Graphics.FromImage(bitmap);
    
    // Add drawing commands here
    g.Clear(Color.Green);
    
    bitmap.Save(@"C:\Users\johndoe\test.png", ImageFormat.Png);
    

    If your Graphics is on a form, you can use this:

    private void DrawImagePointF(PaintEventArgs e)
    {
       ... Above code goes here ...
    
       e.Graphics.DrawImage(bitmap, 0, 0);
    }
    

    In addition, to save on a web page, you could use this:

    MemoryStream memoryStream = new MemoryStream();
    bitmap.Save(memoryStream, ImageFormat.Png);
    var pngData = memoryStream.ToArray();
    
    
    

    Graphics objects are a GDI+ drawing surface. They must have an attached device context to draw on ie either a form or an image.

提交回复
热议问题