Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving System.Drawing.Graphics to a png or bmp

Tags:

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 somehow.

What are the steps?

like image 358
Old Man Avatar asked May 28 '10 12:05

Old Man


People also ask

How do I save a graphics file?

Right-click the illustration that you want to save as a separate image file, and then click Save as Picture. In the Save as type list, select the file format that you want. In the File name box, type a new name for the picture, or just accept the suggested file name. Select the folder where you want to store the image.

What is System drawing bitmap?

Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attributes. A Bitmap is an object used to work with images defined by pixel data.


1 Answers

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();  <img src="data:image/png;base64,@(Convert.ToBase64String(pngData))"/> 

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

like image 76
Curtis Yallop Avatar answered Oct 21 '22 17:10

Curtis Yallop