我正在做.Net Core 2.2。项目并尝试用WebImage
替换已弃用的System.Drawing
进程。我正在尝试调整大小,而大多数情况都可以。问题是当我尝试删除完整尺寸的图像时,它被锁定了:
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
块正在使用所述图像的副本。
初次尝试时,请不要复制,而要使用获得的副本:
using (var image = Image.FromFile(filePath))
关于c# - 使用语句关闭后,System.Drawing图像被锁定,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57312550/