【问题标题】:Issue capturing windows form drawing to image C#问题将 Windows 窗体绘图捕获到图像 C#
【发布时间】:2014-11-23 22:06:33
【问题描述】:

我正在尝试将一些对象绘制到 Windows 窗体,然后创建该窗体的图像并将其保存到文件夹中。

这是一个由两部分组成的问题...为什么绘制到 windows 窗体的图像没有显示在创建的图像上?第二个问题是,我怎样才能创建一个窗口窗体绘图的图像,从点 0,0 到点 500,500 没有背景......

这是我目前拥有的代码......

Form draw = new Drawing();      // Opens the drawing form
draw.Show();

        try
        {
            //Try to draw something...
            System.Drawing.Pen myPen;       
            myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
            System.Drawing.Graphics formGraphics = draw.CreateGraphics();
            formGraphics.DrawLine(myPen, 0, 0, 500, 500);
            myPen.Dispose();
            formGraphics.Dispose();

            var path = this.outputFolder.Text;      // Create variable with output path

            if (!Directory.Exists(path))
            {
                DirectoryInfo di = Directory.CreateDirectory(path);  // Create path if it doesn't exist
            }

            using (var bitmap = new Bitmap(draw.Width, draw.Height))  // Creating the .bmp file from windows form
            {
                draw.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                bitmap.Save(path + "\\" + i + ".bmp");
             }
        }
        catch { }

你能看出这里有什么不对吗?什么似乎禁止将绘图保存到 .bmp 文件?

提前致谢!

【问题讨论】:

  • 你的位图是表格的大小,否则与表格无关;也不确定第一部分与任何事情有什么关系; CreateGraphics 几乎总是将某些东西绘制到表单中的错误方法
  • 什么意思,第一部分什么都没有……能详细点吗?你如何建议我在表单上绘制一些东西,记住它需要稍后保存为图像。
  • you draw 到表单 you 的东西也必须绘制到位图;表单不是一个画布,它会保留在其他地方绘制的内容。如果您不想要背景(这是否意味着表单背景颜色?)然后设置使用 MakeTransparent 来设置它 - 任何具有该颜色的控件在图像中也将是白色/无色。您可能还必须另存为 PNG 以保存透明度
  • 好的,可以这么说,我真的不需要将图像绘制到表单...有没有办法使用类似于 CreateGraphics 的控件,直接绘制到 .bmp 或.png?
  • 我使用了这里的示例 stackoverflow.com/questions/2928845/… 似乎有效!

标签: c# image save drawing


【解决方案1】:

我最终使用了此处显示的示例Saving System.Drawing.Graphics to a png or bmp

        Form draw = new Drawing();      // Opens the drawing form
        draw.Show();
        try
        {
            var path = this.outputFolder.Text; // Path where images will be saved to

            if (!Directory.Exists(path))
            {
                DirectoryInfo di = Directory.CreateDirectory(path);     // Create a directory if it does not already exist
            }

            Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(bitmap);

            System.Drawing.Pen myPen;
            myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
            g.DrawLine(myPen, 0, 0, 1024, 1024);

            bitmap.Save(path + "\\" + i + ".png", ImageFormat.Png);

        }
        catch { }

这对我来说现在完美无缺:D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 2023-04-07
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    相关资源
    最近更新 更多