Csharp/C#教程:将System.Drawing.Graphics保存到png或bmp分享


将System.Drawing.Graphics保存到png或bmp

我有一个我在屏幕上绘制的Graphics对象,我需要将其保存到png或bmp文件中。 图形似乎不直接支持,但必须以某种方式。

步骤是什么?

将其复制到位Bitmap ,然后调用位图的Save方法。

请注意,如果你真的在绘制屏幕(通过抓住屏幕的设备上下文),那么保存刚刚绘制到屏幕上的内容的唯一方法是通过屏幕绘制Bitmap来反转过程。 这是可能的,但显然直接绘制到Bitmap(使用用于绘制到屏幕的相同代码)要容易得多。

这是代码:

 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:Usersjohndoetest.png", ImageFormat.Png); 

如果您的图形在表单上,​​您可以使用:

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

此外,要保存在网页上,您可以使用:

 MemoryStream memoryStream = new MemoryStream(); bitmap.Save(memoryStream, ImageFormat.Png); var pngData = memoryStream.ToArray(); Csharp/C#教程:将System.Drawing.Graphics保存到png或bmp分享 

图形对象是GDI +绘图表面。 它们必须具有附加的设备上下文以进行绘制,即表单或图像。

试试这个,对我来说很好……

 private void SaveControlImage(Control ctr) { try { var imagePath = @"C:Image.png"; Image bmp = new Bitmap(ctr.Width, ctr.Height); var gg = Graphics.FromImage(bmp); var rect = ctr.RectangleToScreen(ctr.ClientRectangle); gg.CopyFromScreen(rect.Location, Point.Empty, ctr.Size); bmp.Save(imagePath); Process.Start(imagePath); } catch (Exception) { // } } 

 Graphics graph = CreateGraphics(); Bitmap bmpPicture = new Bitmap("filename.bmp"); graph.DrawImage(bmpPicture, width, height); 

您可能正在绘制图像或控件。 如果在图像上使用

  Image.Save("myfile.png",ImageFormat.Png) 

如果使用Control.DrawToBitmap()绘制控件,则保存返回的图像,如上所示。

谢谢你的纠正 – 我不知道你可以直接画到屏幕上。

上述就是C#学习教程:将System.Drawing.Graphics保存到png或bmp分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/959777.html

(0)
上一篇 2021年11月24日
下一篇 2021年11月24日

精彩推荐