title: Generating Bitmap of WPF UIElement in ASP.NET
body: <p>I'm trying to generate a bitmap off a WPF border. The whole thing sits in a asp.net app (server side of course) running .net 4.0.</p>
  
  <p>The problem is, that the generated image is, well, empty. Does anyone have an idea why?</p>
  
  <p>Here's the code.</p>
  
  <pre><code>public static byte[] Draw(int width, int height)
      {
          MemoryStream memoryStream
              = new MemoryStream();
          Thread t = new Thread(delegate()
              {
                  System.Windows.Controls.Border border = new System.Windows.Controls.Border()
                  {
                      Background = Brushes.Red,
                      BorderBrush = Brushes.Green,
                      CornerRadius = new System.Windows.CornerRadius(5),
                      Width = width,
                      Height = height
                  };
  
                  border.ApplyTemplate();
  
                  RenderTargetBitmap renderTargetBitmap = 
                      new RenderTargetBitmap(width, height, 90, 90, PixelFormats.Pbgra32);
  
                  renderTargetBitmap.Render(border);
  
                  BitmapEncoder bitmapEncoder = 
                      new PngBitmapEncoder();
  
                  bitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
                  bitmapEncoder.Save(memoryStream);
              });
          t.SetApartmentState(ApartmentState.STA);
          t.Start();
          bool success = t.Join(5000);
  
          if (success)
              return memoryStream.ToArray();
          else
              throw new Exception("Fail");
      }
  </code></pre>
  
  <p>The result is quite bad, as I said the thing returns the image with the right width and height, but it's empty, so I guess I don't mess the thing up with the threading bit.</p>