cwj
cwj

Reputation: 11

GDI+ error when loading a high resolution JPG

I met the common GDI+ error when trying to load a JPG image by C#. I am not sure if it is due to the high resolution of this JPG (46495px*4536px) because loading other low resolution JPG files works fine. The issue JPG file size is 4696KB.

Code:

var newImage = Image.FromFile("demo.jpg"); //issue jpg

It also failed when using Image.FromStream() API:

var stream = File.OpenRead("demo.jpg");

var image = Image.FromStream(stream);

Much appreciation if anyone could help explain

Upvotes: 0

Views: 607

Answers (2)

WonderWorker
WonderWorker

Reputation: 9102

You need the available RAM to store the decompressed image bitmap

On a 32bit display you will require width * height * 4 + c bytes free, where c is unknown depending on the implementation of the drawing classes used.

Example

In your specific case, the calculation is as follows:

46495 * 4536 * 4 + c = 843605280 bytes + c = 805mb + c

Use the following to see how much memory is available for your bitmap.

Include a reference to the VisualBasic dll:

using Microsoft.VisualBasic.Devices;

The method is as follows:

Console.Out.Write(new ComputerInfo().AvailablePhysicalMemory + "bytes free");

...or...

Console.Out.Write((ComputerInfo().AvailablePhysicalMemory / 1048576) + "mb free");

Find c

To find c, use the method above both before AND after an image load.

By loading a number of images successfully and recording the memory used before and after the load.

Experiment by comparing the memory used before and after loading different sizes of image, taking into account the size of the bitmap and you will discover a close approximation of c.

Be aware that all image types are converted to a raw bitmap internally for viewing, regardless of whether it's stored as a .jpg, .png, .gif or whatever. So when I say Bitmp, I'm not referring to the extension .bmp. Instead, I am referring to a bitmp in a literal sense as a raw image file i.e. a map of bits.

Upvotes: 1

BELGOUGI
BELGOUGI

Reputation: 29

the GDI+ will throw an "OutOfMemoryException" if it does not support the pixel format of the file.

Upvotes: 0

Related Questions