Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
658 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:Usersjohndoeest.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...