如果文件太大,Out Of Memory异常

时间:2012-02-20 20:45:15

标签: asp.net out-of-memory

我目前正在对图像进行数据检查。我需要请求尺寸(宽度和高度)和图像的分辨率。超过70MB的文件会导致内存不足和#34; GDI问题的例外。有没有其他方法来获取文件信息?通过FromStream解析它时出现同样的错误...

Using myfile = Image.FromFile(filePath)
...
End Using

2 个答案:

答案 0 :(得分:3)

您可以使用以下代码获取图像属性(仅加载元数据):

using (var fs = new FileStream(@"C:\Users\Dmitry\Pictures\blue-earth-wallpaper.jpg", FileMode.Open, FileAccess.Read)) {
   var decoder = BitmapDecoder.Create(fs, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
   var size = decoder.Frames[0].PixelWidth;
   var height = decoder.Frames[0].PixelHeight;
   var dpiX = decoder.Frames[0].DpiX;
   var dpiY = decoder.Frames[0].DpiY;
}

答案 1 :(得分:0)

我发现此链接http://www.fastgraph.com/help/image_file_header_formats.html告诉您文件中的哪个位置可以找到类型及其尺寸。我想,如果你使用下面这样的东西来寻找并获得前几个字节并在你完成后关闭,那么就不应该使用太多的资源

以下未经测试的代码......

//  This really needs to be a member-level variable;
private static readonly object fsLock = new object();
//  Instantiate this in a static constructor or initialize() method
private static FileStream fs = new FileStream("myFile.txt", FileMode.Open);


public string ReadFile(int fileOffset) {

    byte[] buffer = new byte[bufferSize];

    int arrayOffset = 0;

    lock (fsLock) {
        fs.Seek(fileOffset, SeekOrigin.Begin);

        int numBytesRead = fs.Read(bytes, arrayOffset , bufferSize);

        //  Typically used if you're in a loop, reading blocks at a time
        arrayOffset += numBytesRead;
    }

    // Do what you want to the byte array and close

}