这是我调整图片大小的代码。它工作正常,但当我尝试删除以前创建的时,我有一个错误"文件被另一个进程"使用。这是代码:
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对象但没有成功。任何提示?
答案 0 :(得分:1)
如果没有更多的代码,很难说,但很可能罪魁祸首是你的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();
}
}