Search code examples
c#bitmapgdi+

A generic error occurred in GDI+


I loaded an image into a Picture Box using:

picturebox1.Image = Image.FromFile()

and I save it by using:

Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);

It works perfectly fine when creating a new file, but when I try to replace the existing image, I get thrown the following runtime error:

A generic error occurred in GDI+

So what can I do to solve this problem??


Solution

  • That because the image file is used by your picturebox1.Image, try to save it to different file path instead:

    picturebox1.Image = Image.FromFile(FileName);
    Bitmap bm = new Bitmap(pictureBox1.Image); 
    bm.Save(@"New File Name", ImageFormat.Bmp);
    

    Edit: You could also add a copy from the image at the first place like:

    picturebox1.Image = new Bitmap(Image.FromFile(FileName));
    Bitmap bm = new Bitmap(pictureBox1.Image); 
    bm.Save(FileName, ImageFormat.Bmp);//no error will occurs here.