Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A generic error occurred in GDI+

Tags:

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??

like image 808
Lakshani Avatar asked Aug 18 '11 09:08

Lakshani


2 Answers

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.
like image 109
Jalal Said Avatar answered Sep 21 '22 10:09

Jalal Said


The FromFile method locks the file, so use the Image.FromStream() method for reading the image:

byte[] bytes = System.IO.File.ReadAllBytes(filename);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
pictureBox1.Image = Image.FromStream(ms);

Then save like you were before.

like image 45
KV Prajapati Avatar answered Sep 23 '22 10:09

KV Prajapati