如何修复此错误 "A generic error occurred in GDI+"?

How to Fix this Error "A generic error occurred in GDI+"?

从默认名称打开图像并使用默认名称保存。(覆盖它)

我需要从 Image("Default.jpg") 制作图形并将其放在 picturebox1.image 上并在 picurebox1 上绘制一些图形。(它可以工作,这不是我的问题)但我无法保存picturebox1.Image 覆盖 "Default.jpg"(这是我的问题)。如果我更改保存名称,它可以工作,但我需要覆盖它并多次打开它。 谢谢

    Boolean Play = false;
    Pen P = new Pen(Color.Black, 2);
    Graphics Temp;
    int X1, X2, Y1, Y2;
    Image Default_Image = new Bitmap("Default.jpg");
    public Form1()
    {
        InitializeComponent();
        Temp = pictureBox1.CreateGraphics();
    }
    private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (Play)
        {
            X2 = e.X;
            Y2 = e.Y; ;
            Temp.DrawLine(P, X1, Y1, X2, Y2);
            pictureBox1.Image.Save("Default.jpg");
            Play = false;
        }
        else
        {
            Default_Image = new Bitmap("Default.jpg");
            Temp = Graphics.FromImage(Default_Image);
            pictureBox1.Image =Default_Image;
            X1 = e.X;
            Y1 = e.Y;
            Play = true;
        }
    }

{"A generic error occurred in GDI+."}

覆盖 图像,您需要确保没有 连接到它。 ClosingDisposingCloning 还不够...

这是一个创建真正独立副本的函数:

Bitmap GetClone(string imageName)
{
    if (!File.Exists(imageName)) return null;
    Bitmap bmp2 = null;
    using (Bitmap bmp = (Bitmap)Bitmap.FromFile(imageName))
    {
        bmp2 = new Bitmap(bmp.Width, bmp.Height, bmp.PixelFormat);
        bmp2.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
        using (Graphics g = Graphics.FromImage(bmp2))
        {
            g.DrawImage(bmp, 0, 0);
        }
    }
    return bmp2;
}

现在您可以这样做了:

string file = yourImageFileName;
Bitmap bmp = GetClone(file);
using (Graphics g = Graphics.FromImage(bmp))
{
    // draw what you want..
    g.DrawRectangle(Pens.Red, 11, 11, 199, 199);
}
bmp.Save(file, ImageFormat.Png);  // use your own format etc..

你还应该注意不要泄露旧的 PictureBox.Image 版本。这是一个辅助函数:

void SetPBoxImage(PictureBox pbox, Bitmap bmp)
{
    Bitmap dummy = (Bitmap)pbox.Image;
    pbox.Image = null;
    if (dummy != null) dummy.Dispose();
    pbox.Image = bmp;
}