Working with Copy image or Resize image. You may get error that “A generic error occurred in GDI+”. I have come across to following two codes.
Code 1 :
public void Resize(string oldFilePath, string newFilePath, OrgFile, NewFile)
{
try
{
OrgFile = Path.Combine(Server.MapPath(oldFilePath), OrgFile);
NewFile = Path.Combine(Server.MapPath(newFilePath), NewFile);
System.Drawing.Image OrgImage = System.Drawing.Image.FromFile(OrgFile);
OrgImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
OrgImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
// Resize with height instead
NewWidth = 300;
NewHeight = 300;
System.Drawing.Image ResizedImage = OrgImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
OrgImage.Dispose();
// Save resized picture
ResizedImage.Save(NewFile);
}
catch
{
}
}
Possible reasons of coming error in above code is :
- This error generally caused by providing incorrect save path
- You don’t have folder “newFilePath” physically and as you haven’t written code for create directory, It will throw an error.
- You don’t have write permission on “newFilePath” directory.
- If you are running in local machine then uncheck readonly permission of this folder from your explorer.
- If you have hosted your application then give write permission for IIS user or your hosting account user so that it can save image to that directory.
Code 2 :
public void MyTest()
{
byte[] bt1 = File.ReadAllBytes("img1.jpg");
Stream dtstream= new MemoryStream(bt1);
Bitmap image = new Bitmap(dtstream);
image.Save(@"c:\myimg.jpg");
dtstream.Dispose();
// Now lets use a nice dispose, etc...
Bitmap2 image2;
using (Stream dtstream2= new MemoryStream(bt1))
{
image2 = new Bitmap(dtstream2);
}
image2.Save(@"C:\new folder\myimg2.jpg"); // It will throw the GDI+ exception.
}
First of all above code is created while checking similar error from : http://stackoverflow.com/questions/1053052/a-generic-error-occurred-in-gdi-jpeg-image-to-memorystream
Above code will throw an error because of following reason.
You are disposing the Bitmap and that will close the stream too. Basically once you give the Bitmap constructor a stream, it “owns” the stream and you shouldn’t close it. As the documents for that constructor say:
You must keep the stream open for the lifetime of the Bitmap.
Please comment if you find help from this article.
Thanks dear its working
Its working fine ….thanks a lost…”Possible reasons of coming error in above code is :”