【问题标题】:Convert files to bitmap in C#在 C# 中将文件转换为位图
【发布时间】:2023-03-21 23:25:02
【问题描述】:

我写这段代码从directory(@"D:\\test\\ISIC_2020_Training_JPEG")的文件夹中读取文件,然后在c#中将每个文件转换为位图

foreach (string img in Directory.EnumerateFiles(@"D:\\test\\ISIC_2020_Training_JPEG"))
    Bitmap  bmp = new Bitmap(img);

但是最后一行出现了一个错误,就是:

内存不足异常

这段代码有什么问题?

【问题讨论】:

  • 使用@字符串时,不必转义'\\'
  • 好的,但是这个问题的解决方案是什么?
  • 那有多少个文件,有多大?
  • 文件数=5704,大小在1.42MB到3.3MB之间
  • Out of memory Exception可以在文件格式不正确的情况下抛出,在抛出异常时查看img中的文件名并验证其是有效的图像。

标签: c# image file directory bitmap


【解决方案1】:

我想你在提供的目录上有所有 jpeg 文件,你可以在内存流中加载图像文件,并在内存流中加载图像时检查是否一切正常。

foreach (string imgPath in Directory.GetFiles(@"D:\test\ISIC_2020_Training_JPEG"))
{
    Bitmap  bmp;
    byte[] buff = System.IO.File.ReadAllBytes(imgPath);
    using(System.IO.MemoryStream ms = new System.IO.MemoryStream(buff))
    {
        bmp = new Bitmap(ms);
    }
}
    

【讨论】:

  • 为什么不只是using (var bmp = new Bitmap(imgPath))MemoryStream有什么优势?不批评。只是好奇。
  • 也有同样的问题Out of memory Exception
  • 我用“var”也是同样的问题
  • @JohnnyMopp 没有真正的优势我使用了这个例子,因为它更容易为他调试并查看 ms 在流中是否有任何值和字节长度,你的解决方案更好更简单:)
  • @TJacken 您的代码不会处理位图本身。这一个真正的问题。位图也应该在using 块中。
【解决方案2】:

可能最好的方法是流式传输图像文件,这样如果文件很大,它就不会占用太多内存。然后在尝试转换为Bitmap 之前检查文件格式是否正确,希望这会有所帮助:

Bitmap bitmap;
Image image;
foreach (string imgFile in Directory.EnumerateFiles(@"D:\test\ISIC_2020_Training_JPEG"))
{
    using (Stream bmpStream = File.Open(imgFile, FileMode.Open))
    {
        image = Image.FromStream(bmpStream);
        if (ImageFormat.Jpeg.Equals(image.RawFormat)) // Check it's the correct format
        {
            bitmap = new Bitmap(image);
        }
    }
}

【讨论】:

  • 您没有处理位图本身。只需 using (Bitmap bmp = new Bitmap(path)) { ... } 做同样的事情,正确处理,代码少得多。
猜你喜欢
  • 2013-05-12
  • 2013-06-22
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 2022-01-22
  • 2012-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多