This is a migrated thread and some comments may be shown as answers.

Xaml DrawingBrush converted to show in PictureBox

1 Answer 270 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Paul
Top achievements
Rank 1
Paul asked on 28 Nov 2011, 02:42 PM
I have a XAML drawing brush.  I want it to show in the PictureBox on a report.  But the report only takes an image from System.Drawing and not System.Windows.Media.  Any ideas anyone?

// Grab the XAML DrawingBrush
DrawingBrush db = (DrawingBrush)App.Current.Resources["BugIcon"];
// Create an image (wrong kind of Image though)
Image i = new Image()
{
   Source = new DrawingImage(db.Drawing),
   Height = 300,
   Width = 300
};
// Need to convert Image to System.Drawing.Image.
RenderTargetBitmap renderBmp = new RenderTargetBitmap(300, 300, 96, 96, PixelFormats.Pbgra32);
renderBmp.Render(i);

PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBmp));

using (MemoryStream stream = new MemoryStream())
{
   encoder.Save(stream);
   System.Drawing.Image i2 = System.Drawing.Image.FromStream(stream);
// This is the Telerik report, and the pb1/pb2 are PictureBox controls
   ((Telerik.Reporting.PictureBox)sr.Items["header"].Items["pb1"]).Value = i2;
   ((Telerik.Reporting.PictureBox)sr.Items["header"].Items["pb2"]).Value = i2;
}

1 Answer, 1 is accepted

Sort by
0
Paul
Top achievements
Rank 1
answered on 29 Nov 2011, 06:00 PM
Found it.  Code is below should anyone else need it.

private System.Drawing.Image GetImageFromResource(string s)
{
   // s is a XAML resource stored in the Window or in the Application
   DrawingBrush db = App.Current.Resources[s] as DrawingBrush;

   if (db != null)
   {
      // Create an image (wrong kind of Image though)
      Image i = new Image()
      {
         Height = 300,
         Width = 300,
         Source = new DrawingImage(db.Drawing)
      };

      // Need to render this into a bitmap.  First setting up a DrawingVisual.
      DrawingVisual drawingVisual = new DrawingVisual();
      DrawingContext drawingContext = drawingVisual.RenderOpen();
      drawingContext.DrawImage(i.Source, new Rect(0, 0, 300, 300));
      drawingContext.Close();

      // Now rendering
      RenderTargetBitmap bmp = new RenderTargetBitmap(300, 300, 96, 96, PixelFormats.Pbgra32);
      bmp.Render(drawingVisual);

      // Encode to get the stream
      PngBitmapEncoder encoder = new PngBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(bmp));

      // The stream will contain the image
      using (MemoryStream stream = new MemoryStream())
      {
         encoder.Save(stream);

         // Now generate the correct type of image from this stream
         return System.Drawing.Image.FromStream(stream);
      }
   }

   return null;
}
Tags
General Discussions
Asked by
Paul
Top achievements
Rank 1
Answers by
Paul
Top achievements
Rank 1
Share this question
or