繁体   English   中英

调整大小的图像锁定文件

[英]Resized image locked file

这是我调整图像大小的代码。 它工作正常,但是当我尝试删除以前创建的文件时,出现错误“文件被另一个进程使用”。 这是代码:

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

我试图处理Image对象,但没有成功。 有什么提示吗?

没有更多的代码,这很难说,但是更可能的罪魁祸首是您的fromStream没有关闭并正确处理。 我假设“先前创建”是指您的源流。 尝试将其包装在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