title: A generic error occurred in GDI+, JPEG Image to MemoryStream
body: <p>This seems to be a bit of an infamous error all over the web. So much so that I have been unable to find an answer to my problem as my scenario doesn't fit. An exception gets thrown when I save the image to the stream.</p>
  
  <p>Weirdly this works perfectly with a png but gives the above error with jpg and gif which is rather confusing.</p>
  
  <p>Most similar problem out there relate to saving images to files without permissions. Ironically the solution is to use a memory stream as I am doing....</p>
  
  <pre><code>public static byte[] ConvertImageToByteArray(Image imageToConvert)
  {
      using (var ms = new MemoryStream())
      {
          ImageFormat format;
          switch (imageToConvert.MimeType())
          {
              case "image/png":
                  format = ImageFormat.Png;
                  break;
              case "image/gif":
                  format = ImageFormat.Gif;
                  break;
              default:
                  format = ImageFormat.Jpeg;
                  break;
          }
  
          imageToConvert.Save(ms, format);
          return ms.ToArray();
      }
  }
  </code></pre>
  
  <p>More detail to the exception. The reason this causes so many issues is the lack of explanation :(</p>
  
  <pre><code>System.Runtime.InteropServices.ExternalException was unhandled by user code
  Message="A generic error occurred in GDI+."
  Source="System.Drawing"
  ErrorCode=-2147467259
  StackTrace:
     at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters    encoderParams)
     at System.Drawing.Image.Save(Stream stream, ImageFormat format)
     at Caldoo.Infrastructure.PhotoEditor.ConvertImageToByteArray(Image imageToConvert) in C:\Users\Ian\SVN\Caldoo\Caldoo.Coordinator\PhotoEditor.cs:line 139
     at Caldoo.Web.Controllers.PictureController.Croppable() in C:\Users\Ian\SVN\Caldoo\Caldoo.Web\Controllers\PictureController.cs:line 132
     at lambda_method(ExecutionScope , ControllerBase , Object[] )
     at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
     at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
     at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
     at System.Web.Mvc.ControllerActionInvoker.&lt;&gt;c__DisplayClassa.&lt;InvokeActionMethodWithFilters&gt;b__7()
     at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
   InnerException: 
  </code></pre>
  
  <p>OK things I have tried so far. </p>
  
  <ol>
  <li>Cloning the image and working on that.</li>
  <li>Retrieving the encoder for that MIME passing that with jpeg quality setting.</li>
  </ol>