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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With