Out Of Memory exception on System.Drawing.Image.FromFile()

I have an image uploader and cropper which creates thumbnails and I occasionally get an Out Of Memory exception on the following line:

Dim bm As Bitmap = System.Drawing.Image.FromFile(imageFile)

The occurance of the error is tiny and very rare, but I always like to know what might be causing it. The imageFile variable is just a Server.MapPath to the path of the image.

I was curious if anyone had experience this issue previously and if they had any ideas what might be causing it? Is it the size of the image perhaps?

I can post the code if necessary and any supporting information I have, but would love to hear people’s opinions on this one.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It’s worth knowing that OutOfMemoryException doesn’t always really mean it’s out of memory – particularly not when dealing with files. I believe it can also happen if you run out of handles for some reason.

Are you disposing of all your bitmaps after you’re done with them? Does this happen repeatably for a single image?

Method 2

If this wasn’t a bad image file but was in fact the normal issue with Image.FromFile wherein it leaves file handles open, then the solution is use Image.FromStream instead.

using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
   using (Image original = Image.FromStream(fs))
   {
      ...

Using an explicit Dispose(), a using() statement or setting the value to null on the bitmap doesn’t solve the issue with Image.FromFile.

So if you App runs for a time and opens a lot of files consider using Image.FromStream() instead.

Method 3

I hit the same issue today while creating Thumbnail images for a folder full of images. It turns out that the “Out Of Memory” occured exactly at the same point each time. When I looked at the folder with the images to be converted I found that the file that was creating the problem was thumbs.db. I added some code to make sure that only image files were being converted and the issue was resolved.

My code is basically

For Each imageFile as FileInfo in fileList
If imageFile.Extension = ".jpg" Or imageFile.Extension = ".gif" Then
    ...proceed with the conversion
End If
Next

Hope this helps.

Method 4

Also check if you haven’t opened the same file somewhere else. Apparently, when you open a file twice (even with File.Open()) OutOfMemoryException is thrown too…

Method 5

Also you can open it in read mode, (if you want to use it in two place same time)

 public Image OpenImage(string previewFile)
        {
            FileStream fs = new FileStream(previewFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            return Image.FromStream(fs);
        }

Method 6

This happens when the image file is corrupted. It is a bad error message, because memory has nothing to do with it. I haven;t worked out the coding, but a try/catch/finally will stop the program from abending.

Method 7

I had a similar problem today when I was trying to resize an image and then crop it, what happened is I used this code to resize the image.

private static Image resizeImage(Image imgToResize, Size size)
{
   int sourceWidth = imgToResize.Width;
   int sourceHeight = imgToResize.Height;

   float nPercent = 0;
   float nPercentW = 0;
   float nPercentH = 0;

   nPercentW = ((float)size.Width / (float)sourceWidth);
   nPercentH = ((float)size.Height / (float)sourceHeight);

   if (nPercentH < nPercentW)
      nPercent = nPercentH;
   else
      nPercent = nPercentW;

   int destWidth = (int)(sourceWidth * nPercent);
   int destHeight = (int)(sourceHeight * nPercent);

   Bitmap b = new Bitmap(destWidth, destHeight);
   Graphics g = Graphics.FromImage((Image)b);
   g.InterpolationMode = InterpolationMode.HighQualityBicubic;

   g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
   g.Dispose();

   return (Image)b;
}

And then this code for the crop…

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   Bitmap bmpCrop = bmpImage.Clone(cropArea,
   bmpImage.PixelFormat);
   return (Image)(bmpCrop);
}

Then this is how I called the above code…

Image img = Image.FromFile(@"C:Users****Picturesimage.jpg");
img = ImageHandler.ResizeImage(img, new Size(400, 300));
img = ImageHandler.CropImage(img, new Rectangle(0, 25, 400, 250));
long quality = 90;

I kept getting errors on the crop part, the resizer worked fine!

Turns out, what was happening inside the resizer was throwing errors in the crop function. The resized calculations were making the actual dimensions of the image come out to be like 399 rather than 400 that I passed in.

So, when I passed in 400 as the argument for the crop, it was trying to crop a 399px wide image with a 400px width bmp and it threw the out of memory error!

Most of the above code was found on http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing

Method 8

If an image is an icon then different loading handling is required, like in next function:

public static Image loadImage(string imagePath)
    {
        Image loadedImage = null;
        if (!File.Exists(imagePath)) return loadedImage;
        try
        {
            FileInfo fileInfo = new FileInfo(imagePath);
            if (fileInfo.Extension.Equals(".jpg") || fileInfo.Extension.Equals(".jpeg") ||
               fileInfo.Extension.Equals(".bmp") || fileInfo.Extension.Equals(".png") ||
               fileInfo.Extension.Equals(".gif"))
            {
                loadedImage = Image.FromFile(imagePath);
            }
            else if (fileInfo.Extension.Equals(".ico"))
            {
                Bitmap aBitmap = Bitmap.FromHicon(new
                                           Icon(imagePath, new Size(200, 200)).Handle);
                loadedImage = ImageFuncs.ResizeImage(aBitmap, new Size(30, 30));
            }
        }
        catch (Exception eLocal)
        {
            MessageBox.Show(imagePath + " loading error: " + eLocal.Message);
        }
        return loadedImage;
    }

Method 9

I had the same problem with a utility I wrote to convert TIFF(s) to PDF(s). Often I would get the “out of memory” error on the same line as you.

System.Drawing.Image.FromFile(imageFile)

Then I discovered the error only happened when the file extension was “.tiff” and worked fine after I renamed it with an extension of “.tif”

Method 10

I have had the same issue, before looking else where in the code wanted to make sure if I can open the Image with any Image viewer and figured out that the Image is corrupted/damaged though it’s a .PNG file with 1KB size. Added a new Image in the same location, then It worked fine.

Method 11

I am having same problem batch processing Tiff files. Most of the files aren’t throwing an exception but few files are throwing “Out of Memory” exception in ASP.NET 4.0. I have used binary data to find out why just for few files and from within same folder. It can’t be permission issue for ASP.NET ASPNET or NETWORK SERVICE account because other files are working file.

I have opened iTextSharp.text.Image class and found that there are many overloaded methods for GetInstance(). I have resolved my problem using following code: note: catch block will run for problematic files.

                iTextSharp.text.Image image = null;
            try
                {
                    var imgStream = GetImageStream(path);
                     image = iTextSharp.text.Image.GetInstance(imgStream);
                }
                catch {
                    iTextSharp.text.pdf.RandomAccessFileOrArray ra = null;
                    ra = new iTextSharp.text.pdf.RandomAccessFileOrArray(path);
                    image = iTextSharp.text.pdf.codec.TiffImage.GetTiffImage(ra, 1);

                    if (ra != null)
                        ra.Close();

                }

Method 12

If you’re serving from IIS, try recycling the Application Pool. This solved a similar image upload “Out of Memory” error for me.

Method 13

I created a minimal form example that still gives me errors.

        private void button1_Click(object sender, EventArgs e)
    {
        string SourceFolder = ImageFolderTextBox.Text;
        string FileName = "";
        DirectoryInfo Mydir = new DirectoryInfo(SourceFolder);
        FileInfo[] JPEGS = Mydir.GetFiles("*.jpg");
        for (int counter = 0; counter < JPEGS.Count(); counter++)
        {
            FileName = Mydir + "\" + JPEGS[counter].Name;
            //using (Image MyImage = System.Drawing.Image.FromFile(FileName))
            using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                StatusBtn.BackColor = Color.Green;
            }
        }
    }

I tried both the commented out line using Image.FromFile() as well as the line using FileStream(). Both produced file errors.

The Image.FromFile() error was:
System.OutOfMemoryException: ‘Out of Memory’

The filestream() error was:
System.UnaurthorizedAccessException: ‘Access to the path ‘E:DCIM100Canondsc_7218.jpg’ is denied.

I placed a Breakpoint just prior to the lines producing the error and I am able to open the image file using the Windows image viewer. I then closed the viewer and after I advanced to the next line and get the error, I can no longer view the image with the Windows viewer. Instead, I get a message that I do not have permission to access the file. I am able to delete the file.

This error is repeatable. I’ve done it over 10 times. Each time, after I get the error, I delete the file used for FileName.

All files were verified to be non-corrupt.

My original code that used Image.FromFile() worked fine when I compiled it 2 years ago. In fact, the .exe file runs just fine. I made a minor change somewhere else in the code and was surprised to find that the code would not compile without this error. I tried the FileStream() method based on the information on this page.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x