Pacobart
Pacobart

Reputation: 261

Save Image from Memorystream using C# and ASP.NET

I am using a memory stream to resize an image through a FileUpload control. After it resizes it I want it to save to my filesystem at "~/images/2012/" + filename.

How do I save the image from a memorystream?

System.Drawing.Image imageLarge = System.Drawing.Image.FromStream(stream);
System.Drawing.Image imageLarge1 = ResizeImage(imageLarge, 200, 300);

MemoryStream memolarge = new MemoryStream();
imageLarge1.Save(memolarge, System.Drawing.Imaging.ImageFormat.Jpeg);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(memolarge);

Encoder myEncoder;
EncoderParameter myEncoderParameter;
EncoderParameters myEncoderParameters;
myEncoder = Encoder.Quality;
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;

string convertedImage = returnImage.ToString();
returnImage.Save("~/images/2012/" + filename, 
    ImageFormat.Jpeg, myEncoderParameters);

This is the error I am getting along with an overloaded method error:

cannot convert from 'System.Drawing.Imaging.ImageFormat' to System.Drawing.Imaging.ImageCodecInfo

Upvotes: 2

Views: 10318

Answers (3)

DRobertE
DRobertE

Reputation: 3508

See post Saving as jpeg from memorystream in c# it does something very similar to what you are looking for.

Also to change the codec properly http://msdn.microsoft.com/en-us/library/ytz20d80.aspx

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503599

Look at the overloads of Image.Save.

Only the final two accept EncoderParameters, and neither of them accept an ImageFormat - both accept an ImageCodecInfo.

It's very important to be able to diagnose this kind of problem yourself:

  • Look at the compiler error carefully
  • Read the documentation
  • Check whether the call you're making makes sense

This has nothing to do with saving to a MemoryStream in particular - in fact, it's not clear why you're saving an Image and then immediately loading an Image from the same stream. (I'd advise setting the Position to 0 before you do so anyway, if you really want to keep doing this.)

Upvotes: 4

cdhowie
cdhowie

Reputation: 169413

Try this line instead:

returnImage.Save(
    "~/images/2012/" + filename,
    ImageCodecInfo.GetImageEncoders()
        .Where(i => i.MimeType == "image/jpeg")
        .First(),
    myEncoderParameters);

Upvotes: 2

Related Questions