Search code examples
c#imagesavedevexpressgdi+

a generic error occurred gdi+ c#


i would like to save image with the same name and path after a rotation. i've got an error in the methode save (a generic error occurred gdi+)

Here's the code :

string path = @"mypath";
Bitmap image = new Bitmap(path + aspximage.ImageUrl, true);
image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
//The error is generated here
image.Save(path + aspximage.ImageUrl, ImageFormat.Png);
// I have added this line so that the browser can display it
aspximage.ImageUrl = aspximage.ImageUrl + "&t=" + DateTime.Now.Second;

i get my image from a local path in hard drive. for that i use an ashx handler so my imageUrl is something like "Handler.ashx?n=nameimage.png"

Here's the code of Handler.ashx :

public void ProcessRequest (HttpContext context) {

    string imgName = context.Request.QueryString["n"];
    context.Response.ContentType = "image/png";
    string path = @"myPath" + imgName;
    Image image = Image.FromFile(path);
    image.Save(context.Response.OutputStream, ImageFormat.Png);
}

If i remove this line

// I have added this line so that the browser can display it
aspximage.ImageUrl = aspximage.ImageUrl + "&t=" + DateTime.Now.Second;

My code turns well but the browser is not able to reload my image.

and if i leave it my code works well, but the error is generated after 3 or more execution calls on the same image.

what are your suggestions ?

Thank you for your help.


Solution

  • Finally i found the error.

    I should close the file once i have saved the image in context.Response.outputStream "Handler.ashx"

    for that i added image.Dispose()

    Here's the new code of Handler.ashx :

    public void ProcessRequest (HttpContext context) {
    
        string imgName = context.Request.QueryString["n"];
        context.Response.ContentType = "image/png";
        string path = @"mypath" + imgName;
        Image image = Image.FromFile(path);
        image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        //I added this line
        image.Dispose();
    }