在不将文件锁定在WPF中的情况下获取图像大小

Gab*_*ler 5 c# wpf image

在WPF应用程序中,我在真正加载图像之前先获取了图像大小(宽度和高度)(因为我正在以减小的尺寸加载图像...),并且我正在使用以下C#代码来获取它:

BitmapFrame frame = BitmapFrame.Create(new Uri(path), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
Size s = new Size(frame.PixelWidth, frame.PixelHeight);
Run Code Online (Sandbox Code Playgroud)

效果很好,但随后锁定了我以后要由应用程序删除但无法删除的图像文件。我知道,如果我设置BitmapCacheOption.OnLoad可以解决问题,但是它将加载图像,因此我失去了想要以减小的大小加载图像的优势(使用DecodePixelWidth等)。

因此,有人知道如何在不锁定图像的情况下预先获取图像大小吗?

Ste*_*cya 6

也许你应该在获得图像大小后使用流来使用块来删除锁定

using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
   BitmapFrame frame = BitmapFrame.Create(fileStream , BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
   Size s = new Size(frame.PixelWidth, frame.PixelHeight); 
}
Run Code Online (Sandbox Code Playgroud)