【问题标题】:Saving System.Drawing.Graphics to a png or bmp将 System.Drawing.Graphics 保存为 png 或 bmp
【发布时间】:2016-11-04 00:06:30
【问题描述】:

我在屏幕上绘制了一个 Graphics 对象,我需要将其保存为 png 或 bmp 文件。图形似乎不直接支持这一点,但它一定是可能的。

步骤是什么?

【问题讨论】:

    标签: c# graphics


    【解决方案1】:

    代码如下:

    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);
    

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

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

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

    【讨论】:

    • 我看不出这是如何回答这个问题的,即获取一个 GRAPHICS 对象,并将其复制到位图中。这段代码似乎做了相反的事情。 (我有一种情况,“图形”被传递给一个方法,而“图形”的源在代码中的那个位置无法访问,只能访问“图形”本身。)
    【解决方案2】:

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

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

    【讨论】:

    • 对于未来的读者:尽管有这个问题的标题,但这个答案并没有显示如何将任意 Graphics 对象保存到图像中。也就是说,Graphics 或 Bitmap 中都没有“将其(Graphics 实例)复制到 Bitmap”的函数。从最后一句,它可能是指做Graphics g = Graphics.FromImage(bitmap),然后渲染到那个图形(g),而不是你原来的图形对象。然后你可以做 bitmap.Save 来保存你渲染的内容。
    【解决方案3】:

    试试这个,对我来说很好用...

    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)
        {
            //
        }
    }
    

    【讨论】:

    • 这真的会创建一个 PNG 文件吗?看起来您只是将位图保存到具有 PNG 扩展名的文件中?
    【解决方案4】:
    Graphics graph = CreateGraphics();
    Bitmap bmpPicture = new Bitmap("filename.bmp");
    
    graph.DrawImage(bmpPicture, width, height);
    

    【讨论】:

      【解决方案5】:

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

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

      如果在控件上绘图,请使用 Control.DrawToBitmap() 然后将返回的图像保存为如上。

      感谢您的更正 - 我不知道您可以直接在屏幕上绘图。

      【讨论】:

      • 可以使用 Graphics 直接在屏幕上绘图,它有一个构造函数来获取设备上下文 - 您所需要的只是屏幕的设备上下文。
      • 谢谢你,我从来没有想过直接在屏幕上绘图!
      • 我实际上建议不要直接在屏幕上绘图,因为这样做真的没有意义。
      猜你喜欢
      • 2023-03-15
      • 2014-01-13
      • 2018-12-09
      • 2017-06-11
      • 2020-06-25
      • 2012-06-27
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      相关资源
      最近更新 更多