title: Bitmap.Save, Huge Memory Leak
body: <p>I have an application where I am taking a bitmap and compressing it using a GZipStream and sending it over a socket, all in memory. I have tracked down the dirty scumbag memory leak to the following line:</p>
  
  <pre><code>frame.Save(inStream, jpegCodec, parameters);
  </code></pre>
  
  <p>Browsing around the good ol' information superhighway I have found numerous topics about the Image class leaking memory in the save method on various codecs. Problem is there aren't really any fixes out there that I could find. So my questions are as follows:</p>
  
  <ol>
  <li>What causes this</li>
  <li>How can I fix this</li>
  </ol>
  
  <p>Here is my full Write() method in my FrameStream class where the leak is located.</p>
  
  <pre><code>/// &lt;summary&gt;
      /// Writes a frame to the stream
      /// &lt;/summary&gt;
      /// &lt;param name="frame"&gt;The frame to write&lt;/param&gt;
      public void Write(Bitmap frame) {
          using (EncoderParameter qualityParameter = new EncoderParameter(Encoder.Quality, 50L)) {
              using (EncoderParameters parameters = new EncoderParameters(1)) {
                  parameters.Param[0] = qualityParameter;
  
                  ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                  ImageCodecInfo jpegCodec = null;
  
                  foreach (ImageCodecInfo codec in codecs) {
                      if (codec.MimeType == "image/jpeg") {
                          jpegCodec = codec;
                          break;
                      }
                  }
  
                  using (MemoryStream inStream = new MemoryStream()) {
                      frame.Save(inStream, jpegCodec, parameters); // HUUUGE Memory Leak
                      Byte[] buffer = new Byte[inStream.Length];
                      inStream.Read(buffer, 0, buffer.Length);
  
                      using (MemoryStream outStream = new MemoryStream()) {
                          using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress)) {
                              gzipStream.Write(buffer, 0, buffer.Length);
                          }
  
                          Byte[] frameData = outStream.ToArray();
                          Byte[] packet = new Byte[15 + frameData.Length];
                          Byte[] frameLength = BitConverter.GetBytes(frameData.Length);
  
                          Array.Copy(frameLength, 0, packet, 0, frameLength.Length);
                          Array.Copy(frameData, 0, packet, 15, frameData.Length);
  
                          m_Socket.Send(packet);
                      }
                  }
              }
          }
      }
  </code></pre>