Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write WPF output to image file

Tags:

wpf

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

like image 849
Malcolm Avatar asked Jul 04 '09 11:07

Malcolm


1 Answers

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");
like image 113
ageektrapped Avatar answered Nov 20 '22 03:11

ageektrapped