简体   繁体   English

调整大小的图像锁定文件

[英]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. 我试图处理Image对象,但没有成功。 Any hints? 有什么提示吗?

Without more code, its hard to tell, but more than likely the culprit is your fromStream not being closed and disposed properly. 没有更多的代码,这很难说,但是更可能的罪魁祸首是您的fromStream没有关闭并正确处理。 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语句中,请注意,我还包装了newImage,以便在发生异常的情况下可以正确处理它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM