2

I am receiving an image from the user and want to save it. Initially I do

Stream file = Request.Files[0].InputStream;

Then perform the save where file from the previous step is passed in

using(var image = Image.FromStream(file)) {
    // Set the codec parameters with another method. No Stream involved
    image.Save(filename, codecInfo, codeParam); // Throws GDI+ exception
}

Exception type is : System.Runtime.InteropServices.ExternalException

Exception Message : A generic error occurred in GDI+

StackTrace:

at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)

Have referred other questions where new stream had to be created and kept open but in my case, I already have a input stream. How do I solve this problem?

Abhishek Iyer
  • 604
  • 2
  • 6
  • 18

1 Answers1

1

I had the same problem. I tried different encoder paramaters, different paths but same exception was thrown. It worked for me to save the image first to a memorystream then to a file stream. Here's a snippet.

   using(MemoryStream memoryStream = new MemoryStream())
   using(FileStream fileStream = File.Open(path, FileMode.OpenOrCreate))
   {
   image.Save(memoryStream, yourEncoder, yourEncoderParamaters);
   byte[] imgArray = memoryStream.ToArray();
   fileStream.Write(imgArray, 0, imgArray.Length);
   }
Marko Devcic
  • 1,069
  • 2
  • 13
  • 16