Ras
Ras

Reputation: 628

Resized image locked file

This is my code to resize an image. It works fine but when I try to delete the previously created, I have an error "file is used by another process". This is the code:

try
{
    int newHeight = width * fromStream.Height / fromStream.Width;

    Image newImage = new Bitmap(width, newHeight);
    using (Graphics graphicsHandle = Graphics.FromImage(newImage))
    {
        graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicsHandle.DrawImage(fromStream, 0, 0, width, newHeight);
    }
    string processedFileName = String.Concat(Configuration.CoverLocalPath, @"\Processed\res_", Path.GetFileName(imageFile));
    newImage.Save(processedFileName, ImageFormat.Jpeg);
    newImage.Dispose();

    return processedFileName;
}
catch (Exception ex)
{
    Configuration.Log.Debug("Utility.cs", "ResizeMainCover", ex.Message);
    return string.Empty;
}

I tried to dispose the Image object but without success. Any hints?

Upvotes: 0

Views: 77

Answers (1)

mxmissile
mxmissile

Reputation: 11681

Without more code, its hard to tell, but more than likely the culprit is your fromStream not being closed and disposed properly. I'm assuming "previously created" means your source stream. Try wrapping it in a using statement, note I also wrapped the newImage so it would be disposed properly in case of an Exception.

using(var fromStream = GetSourceImageStream()) 
{ 
    try 
    {
      int newHeight = width * fromStream.Height / fromStream.Width;

      using(Image newImage = new Bitmap(width, newHeight))
      {
        using (Graphics graphicsHandle = Graphics.FromImage(newImage))
        {
          graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
          graphicsHandle.DrawImage(fromStream, 0, 0, width, newHeight);
        }
        string processedFileName = String.Concat(Configuration.CoverLocalPath, @"\Processed\res_", Path.GetFileName(imageFile));
        newImage.Save(processedFileName, ImageFormat.Jpeg);
      }    
      return processedFileName; 
    } 
    catch (Exception ex) 
    {
       Configuration.Log.Debug("Utility.cs", "ResizeMainCover", ex.Message);
       return string.Empty; 
    }
    finally
    {
      fromStream.Close();
    } 
 }

Upvotes: 1

Related Questions