将图像保存到本地路径时出错

问题描述:

我得到一个图像文件,重新调整大小,然后在同一文件夹中保存另一个名称(文件名+ - 调整大小),但是我收到此错误

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;
}