Click here to Skip to main content
15,893,622 members

Getting Out of Memory exception with graphic.DrawImage

Jesse88 asked:

Open original thread
I have an asp:FileUpload (fuInsertImage1) that I'm allowing a user to upload an image to be resized and saved to a server. I grab the image using an InputStream and store it in a Bitmap. I then pass the bitmap into a Resize_Image method. This is for a local news company so the images are high quality, usually 15Mb or larger in size. See code below.

C#
Bitmap bmp;
using(Bitmap temp = System.Drawing.Image.FromStream(fuInsertImage1.PostedFile.InputStream))
bmp = resize_image(temp);
bmp.Save(directory);
bmp.Dispose();

protected Bitmap resize_image(Bitmap img)
{
 //determines if image width is larger that 1024 pixels
 //if yes, resizes image to 1024 width and keeps aspect ratio for height.
 int width, height;
 float percentage = 1; //This is to keep the aspect ratio of the image
 width = img.Width;
 height = img.Height;

 if (width > 1024)
  {
   percentage = (float)1024 / width;
   Bitmap bmp = new Bitmap((int)Math.Round(width * percentage, 0), (int)Math.Round(height * percentage, 0));
   Graphics graphic = Graphics.FromImage((System.Drawing.Image)bmp);

    try
    {
     graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
     graphic.DrawImage(img, 0, 0, (int)Math.Round(width * percentage), (int)Math.Round(height * percentage)); //This is where the exception is thrown.  

     return bmp;
    }
     
    catch (Exception ex)
    {
     return null;
    }

    finally
    {
     bmp.Dispose();
     graphic.Dispose();
    }
   }

   else
   {
    return img;
   }
  }


Can anyone help me figure out why this exception is being thrown or point me in another, more efficient, direction. I have 4GB of Ram in my dev environment also, so I don't think it's a physical memory issue. Any help would be greatly appreciated.
Tags: C# (C# 2.0, C# 3.0, C# 4.0)

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900