Click here to Skip to main content
15,441,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to save an image to the same file it was created from.
Platform: C#.Net.

C#
Bitmap varBmp = (Bitmap)Bitmap.FromFile(@"E:\a.jpg");
 //do something
 varBmp.Save(@"E:\a.jpg");

It shows the following error:
A generic error occurred in GDI+.

How to solve the problem?
How to get the handle of the varBmp image?

Thanks in advance.
Posted
Updated 13-Nov-11 23:26pm
v2

There is a fundamental problem here: Bitmap.FromFile holds a lock on the file until the Bitmap object has been disposed. This means the file is in use when you try to write it, and GDI throws an exception.
The easiest way round this is to copy the bitmap into a second Image object, and dispose the original before you try to overwrite the file.
C#
Bitmap varBmp = (Bitmap)Bitmap.FromFile(@"E:\a.jpg");
Bitmap newBitmap = new Bitmap(varBmp);
varBmp.Dispose();
varBmp = null;
//do something
newBitmap.Save(@"E:\a.jpg");
 
Share this answer
 
Comments
BillWoodruff 15-Nov-11 8:32am    
+5 My guess is there's no way to handle this via a 'Using statement: what do you think ?
thanhtt90 15-Sep-13 11:51am    
Grea..........t Thanks very muuuuch
OriginalGriff 15-Nov-11 8:39am    
Unfortunately not - the documentation is quite clear that the source file remains locked until the actual Bitmap object is Disposed (http://msdn.microsoft.com/en-us/library/stf701f5.aspx) so the only time you can write to it, is after you had thrown away what you wanted to write...:laugh:
mevahid 22-May-13 5:24am    
Greaaaaaaaaaaaaaaaaaaa8.. Thanksssssss
Nirav Prabtani 12-Jul-14 5:36am    
My 5+ Thank you very much Griff, you have solved my problem.. :)
The first thing to check is if the source file is set to read-only ... I know that's probably not likely ...

It would help to know what you have done with the varBmp before you try and re-save: is it possible you've created some object that needs to be disposed, and is not, now, disposed ?

Is it possible you have not wrapped some operation in a Using{} block that needs the auto-dispose implemented by the Using block ?
 
Share this answer
 
v2
I have tried this solution, by disposing the original object it gives the same error.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900