Fantasterei
Fantasterei

Reputation: 462

Out Of Memory exception if files to big

I'm currently working on a data-check for images. I need to request the Size (width & height) and the resolution of the image. Files over 70MB throw an "out of memory" exception on GDI Problem. Is there an alternative way to get the file-information? The same error on parse it through FromStream...

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

Upvotes: 1

Views: 405

Answers (2)

Dmitry Nogin
Dmitry Nogin

Reputation: 3750

You can use the following code to get image properties (it loads metadata only):

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;
}

Upvotes: 3

Krishna
Krishna

Reputation: 2481

I found this link http://www.fastgraph.com/help/image_file_header_formats.html that tells where in the file you can find the type and its dimensions. I guess, if you use something like this below to seek and get the first few bytes and close once you are done, shouldnt be using much resources

Untested code below...

//  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

}

Upvotes: 0

Related Questions