OutOfMemoryException C# When Uploading Image Files


OutOfMemoryException C# When Uploading Image Files



I have been working on an image gallary. When the user uploads an Image I now check the size of the file. If it is less than 1MB I check to see that the file is actually an image type. Finally I resize the image to an appropriate gallary size, and create a small thumbnail of the image. However since adding in the code to check the types I have been experiancing and OutOfMemoryException.

Here's my controller method:

        [AcceptVerbs(HttpVerbs.Post)]     public ActionResult Upload(Image image, HttpPostedFileBase ImageFile)     {          if (ImageFile.ContentLength > 0)         {             // Get the size in bytes of the file to upload.             int fileSize = ImageFile.ContentLength;              // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.             if (fileSize < 1048576)             {                 string fileclass = "";                  using (BinaryReader r = new BinaryReader(ImageFile.InputStream))                 {                     byte buffer = r.ReadByte();                     fileclass = buffer.ToString();                     buffer = r.ReadByte();                     fileclass += buffer.ToString();                     r.Close();                 }                  switch (fileclass)                 {                     case "7137":                     case "255216":                     case "13780":                         try                         {                             string path = Server.MapPath("~/Uploads/");                              ImageFile.SaveAs(path + ImageFile.FileName);                              ResizeImageHelper resizeImageHelper = new ResizeImageHelper();                             resizeImageHelper.ResizeImage(path + ImageFile.FileName, path + ImageFile.FileName, 640, 480, false);                             resizeImageHelper.ResizeImage(path + ImageFile.FileName, path + "thumb" + ImageFile.FileName, 74, 74, false);                              image.imageLocation = ImageFile.FileName;                             image.imageThumb = "thumb" + ImageFile.FileName;                              imageRepository.Add(image);                             imageRepository.Save();                              return RedirectToAction("Index", "Home");                         }                         catch (Exception ex)                         {                             return View("Error");                         }                 }              }             else             {                 //If file over 1MB                 return View("Error");             }         }         else         {             //If file not uploaded             return View("Error");         }          return View("Error");     } 

And here is the Resize method I use:

public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)     {         System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);          // Prevent using images internal thumbnail         FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);         FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);          if (OnlyResizeIfWider)         {             if (FullsizeImage.Width <= NewWidth)             {                 NewWidth = FullsizeImage.Width;             }         }          int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;         if (NewHeight > MaxHeight)         {             // Resize with height instead             NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;             NewHeight = MaxHeight;         }          System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);          // Clear handle to original file so that we can overwrite it if necessary         FullsizeImage.Dispose();          // Save resized picture         NewImage.Save(NewFile);     } 

Can anyone advise with this? I am currently just playing around trying to learn new things :-)

Thanks,

Jon

Progress I have narrowed it down to this block, when commented out things function as normal:

using (BinaryReader r = new BinaryReader(ImageFile.InputStream))                 {                     byte buffer = r.ReadByte();                     fileclass = buffer.ToString();                     buffer = r.ReadByte();                     fileclass += buffer.ToString();                     r.Close();                  } 

How can I determine the current controller action in an mvc sitemap?

1:

Check ASP.NET MVC values (roles) from client (jQuery)
I'm assuming this doesn't appear the first run through, although after any time. Building a repeatable HTTP request parameterIs this correct?. “ASP.NET Webforms MVP” as an alternative to “ASP.NET MVC” [closed] edit: removed incorrect assumption, although there's still an issue with IDisposable. Asp.net Mvc Routing problem You're not disposing of NewImage, and this will cause you issues in production.. How to dynamically determine which HTML 'wrapper' file to use based on the Action Method being executed? I'd normally say 'just use a using', although try/finally is the same thing. Can an Action Filter have access to a private object in the Controller?Refactor to us a using at your own discretion.. Is it possible to optimize ASP.NET WebForms to perform as fast as ASP.NET MVC?
System.Drawing.Image NewImage = null; System.Drawing.Image FullsizeImage = null;  try {     FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);       [... snip ... ]      NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);      // Clear handle to original file so this i must overwrite it if necessary     FullsizeImage.Dispose();      // Save resized picture     NewImage.Save(NewFile); } finally {     if (FullsizeImage != null)         FullsizeImage.Dispose();     if (NewImage != null)         NewImage.Dispose(); } 

2:

Ok Guys after discovering this part of the code was the problem:.
using (BinaryReader r = new BinaryReader(ImageFile.InputStream))             {                 byte buffer = r.ReadByte();                 fileclass = buffer.ToString();                 buffer = r.ReadByte();                 fileclass += buffer.ToString();                 r.Close();              } 
I changed it to this:.
string fileclass = ImageFile.ContentType.ToString(); 
And altered my switch statement to:.
switch (fileclass)                 {                     case "image/jpg":                     case "image/jpeg":                     case "image/png":                     case "image/gif":                         try 
I also implemented the suggestions from Robert. However I am unsure being new to .NET whether this method of checking the file type is as accurate as the previous? My research seems to suggest the previous could discover the file type even if the up loader had changed the extension e.g. renaming example.exe to example.jpg. I am unsure as to whether using the provided .NET functionality the same is still achieved? .


54 out of 100 based on 24 user ratings 54 reviews

@