我正在做 .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/