Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

c# - Saving System.Drawing.Graphics to a png or bmp

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...