【问题标题】:How to read image dimensions at C# wpf - there is no dispose method for BitmapImage如何在 C# wpf 中读取图像尺寸 - BitmapImage 没有 dispose 方法
【发布时间】:2013-03-17 10:56:00
【问题描述】:

通过以下方式我能够阅读。

但是没有 dispose 方法,所以我以后无法删除文件。

所以下面的方法失败了。

我想不出合适的解决方案。

位图类在 C# 4.5 WPF 应用程序中无法识别。

谢谢

    DirectoryInfo dInfo = new DirectoryInfo(@"C:\pokemon_files\images\");
    FileInfo[] subFiles = dInfo.GetFiles();

    BitmapImage myImg;
    foreach (var vrImage in subFiles)
    {
        string srFilePath = vrImage.FullName;
        System.Uri myUri = new Uri(srFilePath);
        myImg = new BitmapImage(myUri);

        if (myImg.Width < 50)
        {
            File.Delete(srFilePath);
            continue;
        }
     }

【问题讨论】:

标签: c# wpf image .net-4.5 bitmapimage


【解决方案1】:

我认为你得到的错误是由于试图删除当前正在使用的文件引起的 通过位图(我不记得异常名称)。

对此有一个解决办法,那就是:制作一个字节流。

byte[] imageData;

using(var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using(var binaryReader = new BinaryReader(fileStream))
{
    imageData = binaryReader.ReadBytes((int)fileStream.Length);
}

var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(imageData);
bitmap.EndInit();

//Now you can check the width & height, the file stream should be closed so you can
//delete the file.

[编辑] 如果您不想读取BinaryReader 的字节,如果您想从文件中读取所有字节,则始终有this solution

【讨论】:

  • 您应该始终检查从ReadBytes 方法收到的字节数。
猜你喜欢
  • 1970-01-01
  • 2017-04-06
  • 2011-01-27
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 2011-04-03
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多