title: How to decode image from stream, into existing image
body: <p>I have an application which plays audio with NAudio. A known limitation with NAudio is that every time the Garbage Collector runs, every thread is paused until it is done.</p>
  
  <p>The application runs fine, all GC is done within acceptable time and there is no stuttering.</p>
  
  <p>But we also have an separate application that sends a thumbnail to the main application (with the audio player) over TCP every second. The Thumbnail is about 1300 bytes when encoded as JPEG.</p>
  
  <p>This is the code we are currently using to decode the image:</p>
  
  <pre><code>MemoryStream ms = new MemoryStream(data);
  BitmapDecoder bdec = BitmapDecoder.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.Default);
  BitmapSource source = bdec.Frames[0];
  imgPreview.Source = source;
  </code></pre>
  
  <p>And to encode:</p>
  
  <pre><code>JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
  jpgEncoder.QualityLevel = quality;
  jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
  
  byte[] imageArray;
  using (MemoryStream outputStream = new MemoryStream())
  {
      jpgEncoder.Save(outputStream);
      imageArray = outputStream.ToArray();
  }
  </code></pre>
  
  <p>Where RenderTarget is a RenderTargetBitmap that have the image content.</p>
  
  <p>Right now we are creating and throwing away a MemoryStream, a BitmapDecoder, and a BitmapSource every second. I have commented out lines from the code and it looks like the MemoryStream and the BitmapDecoder constructor does not create any stutter, but once it's accessed through Frames[0], it starts to stutter.</p>
  
  <p>We have also tried this approach instead of the BitmapDecoder, but with same results:</p>
  
  <pre><code>img.BeginInit();
  img.StreamSource = ms;
  img.EndInit();
  </code></pre>
  
  <p>Surely there is a better way to continuously update an image?</p>
  
  <p>The best way would be to just send over the raw image data, and create a WriteableBitmap, which are just rewritten every second. But the raw image is 170 kb, over 100 times more than the encoded image, and we really don't want to do that. Is it possible to decode a JPEG stream into an existing byte array, or existing image?</p>