title: Save an image in its respective format to a stream
body: <p>I have a challenge that involves multiple parts, most of which I have no problem with. I need a function that reads an image stream, automatically resizes it to a specified size, compresses the image to a specific leve (if applicable) and then returns the image stream, but also keeping the original image format and keep transparency (if there is any.)</p>
  
  <p>This involves a simple resize function, which works I have no problem with.</p>
  
  <p>It involves reading the original image format, and this code seems to work:</p>
  
  <pre><code>// Detect image format
  if (newImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
  {
        //etc for other formats
  }
  //etc
  </code></pre>
  
  <p>Returning the image stream is where I'm stuck. I can return a stream with the compression, but it defaults to to Jpeg. I don't see where to specify the format. And when I do specify format by saving the image twice, I am losing the transparency.</p>
  
  <p>I guess there are two questions:</p>
  
  <p>1) If I resize the image, do I also need to rebuild the alpha transparency on a PNG?
  2) How can I save to a memory stream in the respective format while keeping transparency when necessary?</p>
  
  <p>Here's my broken code!</p>
  
  <pre><code>System.Drawing.Imaging.ImageCodecInfo[] Info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
  System.Drawing.Imaging.EncoderParameters Params = new System.Drawing.Imaging.EncoderParameters(1);
  long ImgComp = 80;
  Params.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImgComp);
  
  MemoryStream m_s = new MemoryStream();
  // Detect image format
  if (newImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
  {
      newBMP.Save(m_s, ImageFormat.Jpeg);
  }
  else if (newImage.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
  {
      newBMP.Save(m_s, ImageFormat.Png);
  }
  
  // Save the new graphic file to the server
  
  newBMP.Save(m_s, Info[1], Params);
  retArr = m_s.ToArray();
  </code></pre>