tags:

views:

499

answers:

4

Hi,

Is there a way I can write the output of WPF say a canvas to a image file, jpg or the like.

I want to use WPF to create a background for me as I want to use the BitmapEffects for a rectangle and also radius the corners.

I want to use the bitmap in a webpage.

Is this possible?

Malcolm

+2  A: 

The RenderTargetBitmap class will convert any WPF visual (including a canvas) into a bitmap.

Guy Starbuck
+4  A: 

I have a blog post all about this here. Here's the code from the article:

   Rect rect = new Rect(canvas.RenderSize);
   RenderTargetBitmap rtb = new RenderTargetBitmap((int)rect.Right,
     (int)rect.Bottom, 96d, 96d, System.Windows.Media.PixelFormats.Default);
   rtb.Render(canvas);
   //encode as PNG
   BitmapEncoder pngEncoder = new PngBitmapEncoder();
   pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

   //save to memory stream
   System.IO.MemoryStream ms = new System.IO.MemoryStream();

   pngEncoder.Save(ms);
   ms.Close();
   System.IO.File.WriteAllBytes("logo.png", ms.ToArray());
   Console.WriteLine("Done");
ageektrapped
A: 

I think someone on the wpf blogroll blogged about it earlier today. When using stackpanels the layout-sweep messes upp the rendertargetbitmap stuff. så best practice is to create a visualbrush of the actual stuff and render that to a bitmapsource

ah. found it. Jaime Rodriguez blogged about it.

Simon Söderman
A: 

When I print the write the image out it is correct but it is offset by the size of the margins.