【问题标题】:How to save the painted control as a bitmap?如何将绘制的控件保存为位图?
【发布时间】:2014-05-10 22:13:17
【问题描述】:

我有一个图片框(pictureBox1),它从绘画事件中获取线条。我想知道如何将该图形(带有线条)转换为位图,并将其保存为文件。我试过了:

Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox.Height);
pictureBox1.DrawToBitmap(bmp, pictureBox1.Bounds);
bmp.Save("MyImage.bmp");

但那是一张空白图片,没有线条。有谁知道我可以用线条保存它吗?谢谢。

【问题讨论】:

  • 不要使用 CreateGraphics(),而是使用 Paint 事件。
  • 我没有,而pictureBox1 是从paint 事件中绘制的。 @汉斯帕桑特

标签: c# bitmap paint


【解决方案1】:
            int bitmapX = 100
            int bitmapY = 100

            Bitmap imgToSave = new Bitmap(bitmapX, bitmapY);
            Graphics gfx = Graphics.FromImage(imgToSave);

            // draw on the image with
            gfx.DrawLine() // or whatever you want to draw

            // save the screenshot
            string saveFilePath = Application.StartupPath + "\<name of the image>.png";
            imgToSave.Save(saveFilePath, ImageFormat.Png);

这是一个适合我的代码 sn-p。

【讨论】:

    【解决方案2】:

    不要使用PictureBox.Bounds property,而是使用简单的Rectangle object/structure 填充`PictureBox' 的宽度和高度,如下所示:

    var bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    pictureBox1.DrawToBitmap(bitmap, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
    bitmap.Save("c:\\temp\\image.bmp");
    

    使用Bounds 属性,您正在获取图片框控件的正确大小,但取决于位置不是0,0 坐标,而是控件位置,这会导致位图为空。

    【讨论】:

    • 我不知道这是否适用于我的情况,因为我使用paint事件在控件pictureBox1上绘制线条。
    • 我已经更新了我的答案,当您使用绘制事件图形对象绘制到图片框控件(而不是使用图像)时,代码有效。
    猜你喜欢
    • 2013-02-03
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多