如何将绘制的控件保存为位图?

时间:2014-05-10 22:13:17

标签: c# bitmap paint

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

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

但这是一张空白的图像,没有线条。有谁知道如何用线条保存它?谢谢。

2 个答案:

答案 0 :(得分:0)

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

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坐标,而是控制位置,这会导致空位图。< / p>

答案 1 :(得分:0)

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

这是一个适合我的代码段。

相关问题