I get an image file, re-size it and then save with a different name in the same folder ( filename+"-resize" ), but I get this error
A generic error occurred in GDI+
Here is my code for resizing method ,
private string resizeImageAndSave(string imagePath)
{
System.Drawing.Image fullSizeImg
= System.Drawing.Image.FromFile(Server.MapPath(imagePath));
var thumbnailImg = new Bitmap(565, 290);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, 565, 290);
thumbGraph.DrawImage(fullSizeImg, imageRectangle);
string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
thumbnailImg.Save(targetPath, ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
thumbnailImg.Dispose();
return targetPath;
}
I want to know how to fix it ?
As others said, it could be a permission problem or the directory might not exist. However, you could try cloning the image before saving it. This could fix the issue if the above is not the problem.
private static string resizeImageAndSave(string imagePath)
{
System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath(imagePath));
var thumbnailImg = new Bitmap(565, 290);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, 565, 290);
thumbGraph.DrawImage(fullSizeImg, imageRectangle);
fullSizeImg.Dispose(); //Dispose of the original image
string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
Bitmap temp = thumbnailImg.Clone() as Bitmap; //Cloning
thumbnailImg.Dispose();
temp.Save(targetPath, ImageFormat.Jpeg);
temp.Dispose();
return targetPath;
}
After this line of code...
string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
Try this please...add image name with extension
if (!Directory.Exists(targetPath))
Directory.CreateDirectory(targetPath);
//now do the rest and place image name and extension...
thumbnailImg.Save(targetPath + @"\img.jpg", ImageFormat.Jpeg);
thumbnailImg.Dispose();
return targetPath;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With