在同一路径上多次保存bmp图像C#

时间:2012-06-12 15:18:35

标签: c#-2.0

所以,我正在处理我的绘画应用程序。每次进行更改时,都会复制当前屏幕状态并将其保存为磁盘上的位图图像(因此我可以在我的绘图事件中使用它)。

当我最小化并将窗口恢复到正常状态然后尝试绘制时,会出现问题。这会触发我的事件对更改做出反应,程序会尝试保存图像---->>> kabooom。

它说“GDI +中发生了一般性错误”。所以,我一直在浏览各种论坛寻找答案,但没有一个给我真正的答案,他们都提到错误的路径等但我是很确定这不是问题。我是否必须处理位图或对流做一些事情?

        int width = pictureBox1.Size.Width;
        int height = pictureBox1.Size.Height;

        Point labelOrigin = new Point(0, 0); // this is referencing the control
        Point screenOrigin = pictureBox1.PointToScreen(labelOrigin);

        int x = screenOrigin.X;
        int y = screenOrigin.Y;

        Rectangle bounds = this.Bounds;
        using (Bitmap bitmap = new Bitmap(width, height))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(new Point(x, y), Point.Empty, bounds.Size);
            }
            bitmap.Save(_brojFormi + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);                
        }

1 个答案:

答案 0 :(得分:0)

将图像保存到磁盘,以便在其他事件中使用它?哇。

为什么不使用类全局变量来存储位图?

class MyForm
{
    Bitmap currentImage = null;
    Graphics gfx = null;

    private void btnLoad_Click(object sender, EventArgs e)
    {
        // ...
        currentImage = new Bitmap(fileName);
        gfx = Graphics.FromImage(currentImage);
    }

    private void pbEditor_Paint(object sender, PaintEventArgs e)
    {
        if (currentImage != null && gfx != null)
        {
             lock(currentImage) e.Graphics.DrawImage(currentImage, ...);
        }
    }

    private void pbEditor_Click(object sender, MouseEventArgs e)
    {
        // quick example to show bitmap drawing
        if (e.Button == MouseButtons.Left)
            lock(currentImage) currentImage.SetPixel(e.Location.X, e.Location.Y, Colors.Black);
    }
}