title: Create thumbnail image directly from header-less image byte array
body: <p>My application shows a large number of image thumbnails at once. Currently, I am keeping all full size images in memory, and simply scaling the image in the UI to create the thumbnail. However, I'd rather just keep small thumbnails in memory, and only load the fullsize images when necessary.</p>
  
  <p>I thought this would be easy enough, but the thumbnails I'm generating are terribly blurry compared to just scaling the fullsize image in the UI.</p>
  
  <p>The images are byte arrays with no header information. I know the size and format ahead of time, so I can use BitmapSource.Create to create an ImageSource.</p>
  
  <pre><code> //This image source, when bound to the UI and scaled down creates a nice looking thumbnail
   var imageSource = BitmapSource.Create(
       imageWidth,
       imageHeight,
       dpiXDirection,
       dpiYDirection,
       format,
       palette,
       byteArray,
       stride);
  
  using (var ms = new MemoryStream())
  {
      PngBitmapEncoder encoder = new PngBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(imageSource);
      encoder.Save(ms);
  
      var bi = new BitmapImage();
      bi.BeginInit();
      bi.CacheOption = BitmapCacheOption.OnLoad;
  
      //I can't just create a MemoryStream from the original byte array because there is no header info and it doesn't know how to decode the image!
      bi.StreamSource = ms;
      bi.DecodePixelWidth = 60;
      bi.EndInit();
  
      //This thumbnail is blurry!!!
      Thumbnail = bi;
  }
  </code></pre>
  
  <p>I'm guessing its blurry since I'm converting it to png first, but when I use the BmpBitmapEncoder I get that "No imaging component available" error. In this case my image is Gray8, but I'm not sure why the PngEncoder can figure it out but the BmpEncoder can't.</p>
  
  <p>Surely there must be someway to create a thumbnail from the original ImageSource without having to encode it to a bitmap format first? I wish BitmapSource.Create just let you specify a decode width/height like the BitmapImage class does.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The final answer is to use a TransformBitmap with a WriteableBitmap to create the thumbnail and eliminate the original, full-size image.</p>
  
  <pre><code>var imageSource = BitmapSource.Create(...raw bytes and stuff...);
  var width = 100d;
  var scale = width / imageSource.PixelWidth;
  WriteableBitmap writable = new WriteableBitmap(new TransformedBitmap(imageSource, new ScaleTransform(scale, scale)));
  writable.Freeze();
  
  Thumbnail = writable;
  </code></pre>