0

Brief

I want to display a PNG image in my PictureBox. At runtime the software asks the path of the image from the user.

Solution i am using

This is my code uptill now

picturebox1.Image = null;
OpenFileDialog ofDlg = new OpenFileDialog();
ofDlg.Filter = "Image files|*.png";
if (DialogResult.OK == ofDlg.ShowDialog())
{
     picturebox1.Image = Image.FromFile(ofDlg.FileName); //Out of memory.
}

Problem

It was all working fine uptill now untill i got an image which was of 25.7 MB (8827 x 11350 pixels).

I know you might all suggest that i should get a lighter version of this image BUT the problem is that this software is used to zoom the image to view the image in detail. So i cannot resize it at any cost.

Now whenever i run the above code it gives me the exception

Out of memory.

I do not understand what is the problem here because i have 8GB of RAM installed on my PC then how it is out of memory? Below is my CPU usage at the time when this error message appeared.

enter image description here

Agent_Spock
  • 1,107
  • 2
  • 16
  • 44

1 Answers1

2

Follow the sugestions of all the comments, i.e Make sure you are in 64 bit

But you need to also make sure you are disposing your images or you will run out of memory sooner or later anyway. The following is just an exmaple

if(picturebox1.Image != null)
   picturebox1.Image.Dispose();

picturebox1.Image = null;

OpenFileDialog ofDlg = new OpenFileDialog();
ofDlg.Filter = "Image files|*.png";
if (DialogResult.OK == ofDlg.ShowDialog())
{
     picturebox1.Image = Image.FromFile(ofDlg.FileName); //Out of memory.
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • this actually worked BUT i do not understand why it worked? was it keeping every image in the memory that has been set to picturebox? because i never saw increment of RAM usage after every image view. – Agent_Spock Jul 04 '18 at 08:23
  • @Agent_Spock Yeah a lot of bad things happen when you dont dispose images, first is a big memory leak, however the second is that you have unmanaged file handles and such hanging around if you read them from disk – TheGeneral Jul 04 '18 at 08:25
  • sorry i am not a professinal like you but how "unmanaged file handles" still lurk around when i have changed my image? – Agent_Spock Jul 04 '18 at 08:27
  • 1
    Because the image keeps a reference to them from the operating system until you dispose them and it cleans it self up. by not disposing you are never allowing the image to clean itself up, things are'nt going out of memory in a variety of different ways – TheGeneral Jul 04 '18 at 08:29
  • It's not a memory issue, it's a O/S graphics handle issue. – Enigmativity Jul 04 '18 at 09:08
  • GDI Process Handles to be precise. – Enigmativity Jul 04 '18 at 09:13
  • 1
    @Enigmativity yeah gdi handle, file handle, any managed memory, however yeah the out of memory is gdi – TheGeneral Jul 04 '18 at 09:14