3

When using the code below I sometimes get the error "A generic error occurred in GDI+. at System.Drawing.Image.Save". I've started to believe that it's because I delete the source image before saving the newly created image. Is that the case? When is it really safe to delete a source Image file then?

The sub class:

thumbnailImage = GetThumb();
thumbnailImage.Save(fullDestinationFilename);

The base class:

public virtual Image GetThumb() {
    using (var image = Image.FromFile(sourceFile)) {
        thumbImage = Crop(image, BrowserWidth, BrowserHeight));
    }
    File.Delete(sourceFile);
    return thumbImage;
}

private static Image Crop(Image image, int width, int height) { 
    var croppedImage = new Bitmap(width, height);
    using (var g = Graphics.FromImage(croppedImage)){
        g.DrawImage(image, 0, 0, image.Width, image.Height);
       return croppedImage;
   }

}

7
  • If you load an Image/Bitmap from file, you cannot delete that instance's source. Not sure about the exact detail, but it is a known 'quirk'.
    – leppie
    Commented Mar 19, 2012 at 12:45
  • I realized I could test to not delete the source file at all, so I did that but the Exception is still thrown sometimes. I'm clueless at the moment. Commented Mar 19, 2012 at 13:19
  • It is not your code. Deleting files can be tricky, there might be another process that's looking at the file. A possible workaround is to rename the file before deleting it. If the delete fails then you can stomp it next time by deleting the renamed file first. Commented Mar 19, 2012 at 13:25
  • The deletion of the file isn't the problem, it's the saving of the new image created from the original image (sourceFile). Commented Mar 19, 2012 at 13:37
  • Might it be the Crop method? Is it bad to dispose the graphics object and then return the image? Commented Mar 19, 2012 at 13:53

2 Answers 2

0

I think I've got it to work now. The problem didn't lie in the code I showed you. After saving the thumbnail to file I wrote it to the http response stream and DID NOT DISPOSE the thumbnail image. When another request that resulted in a save on that file came in it couldn't overwrite the image file because it was still locked from the last request.

-1

Did you try something like this

public virtual Image GetThumb() {
    using (var image = Image.FromFile(sourceFile)) {
        thumbImage = Crop(image, BrowserWidth, BrowserHeight));
    }
    if(thumbImage != null)
    {     
      File.Delete(sourceFile);
    }
    return thumbImage;
}

Also I think it is better if you use try catch statement.

1
  • This is not an answer, it's a question/guess. One that is wrong, btw.
    – leppie
    Commented Mar 19, 2012 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.