c# - System.Drawing 图像在使用语句关闭后被锁定

标签 c# .net-core

我正在做 .Net Core 2.2。项目并尝试用 System.Drawing 替换已弃用的 WebImage 进程。我正在尝试调整大小,所有这些基本上都可以。问题是当我尝试删除全尺寸图像时,它被锁定了:

var userId = _userManager.GetUserId(User);
string filePath = serverPath + "\\" + userId + ".png";
string filePathResized = serverPath + "\\" + userId + "_resized.png";

using (var stream = new FileStream(filePath, FileMode.Create))
{
    await file.CopyToAsync(stream);
}
//<-- not locked here
using (var image = new Bitmap(Image.FromFile(filePath))) //<-- locks here
{
    var width = image.Width;
    var height = image.Height;
    double ratio = height / (double)width;

    var resizedImage = new Bitmap(AvatarScreenWidth, (int)(AvatarScreenWidth * ratio));
    using (var graphics = Graphics.FromImage(resizedImage))
    {
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.DrawImage(image, 0, 0, AvatarScreenWidth, (int)(AvatarScreenWidth * ratio));

    }

    resizedImage.Save(filePathResized, ImageFormat.Png);
}   //<----- should be closed here?

if (System.IO.File.Exists(filePath))
{
    System.IO.File.Delete(filePath);  //<--- fails here because of locked file
}

return Path.GetFileName(filePathResized);

根据我对其他 SO 问题和答案的理解,当 using 语句关闭时,文件应该解锁。调整大小后的文件已关闭,但原始文件已锁定,直到我停止调试器。

有人知道我做错了什么吗?

最佳答案

我实际上并没有测试它,但看起来你实际上并没有处理你用 Image.FromFile 创建的图像。您的 using block 正在使用所述图像的副本。

作为第一次尝试,不要复制,而是使用你得到的:

using (var image = Image.FromFile(filePath))

关于c# - System.Drawing 图像在使用语句关闭后被锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312550/

相关文章:

c# - 处理合并的业务和表示代码的最佳方式?

c# - TSQL:生成人类可读的 ID

asp.net-core - .NET Core API 请求与支持的文件类型不匹配

c# - .net core API 文件上传无法在 Azure 上运行

c# - 将 HttpModule .Net 类库移植到 .Net Core Web API

testing - vscode-dotnet-test-explorer 调试测试 "Waiting for Process to Attach"

c# - 异步和等待需要澄清

c# - 页面加载后脚本不工作

c# - 如何将 JSON 结果返回到 Ajax.BeginForm

.net - 将基于.net core 5.0的python 3.8安装到Docker