Click here to Skip to main content
14,636,795 members
Articles » Platforms, Frameworks & Libraries » Windows Presentation Foundation » General
Posted 9 Oct 2008


29 bookmarked

How to generate a WPF image and render it in a Webpage

Rate this:
4.17 (7 votes)
Please Sign up or sign in to vote.
4.17 (7 votes)
9 Oct 2008CPOL
WPF Image generation


The following code example will show you how to generate a basic image with WPF and render it to a webpage. It will cover the major issues encountered during the development of this solution.


During a project I worked on, we needed to generate an image that contained live data so that when we emailed our client base, an image was rendered from a snap shot of data within our database. This image was embedded into an email so that even if you opened it up a day late it would be live, relevant and data specific to the person reading it. The great thing about this solution is that you could even code your image to generate according to the time the email was open, so if your client opens it a week late you could offer him the current offers or specials.

Using the code

Bellow is a basic aspx web page that will host the binary output of the WPF application. You will need to create an STA thread so as to comunicate with the WPF project.

public partial class _Default : System.Web.UI.Page
 private Byte[] _bufferMain;
 public Byte[] BufferMain
 get { return _bufferMain; }
 set { _bufferMain = value; }
public void Page_Load(object sender, EventArgs e)
 if (!IsPostBack)
  Response.ContentType = @"image/jpeg";
  Response.BufferOutput = true;
public void DisplayDialog()
    Thread worker = new Thread(new ThreadStart(DisplayDialogInternal));
  worker.Name = "DisplayDialog";
catch (Exception exp)
public void DisplayDialogInternal()
  string fileName = @"C:\TestWeb.jpg";
  RenderBookingGridImage image = new RenderBookingGridImage();
  //en-code image to transport 
  BufferMain = image.RenderImage("TESTVALUE");
  Stream st = new MemoryStream(BufferMain);
  //de-code view
  JpegBitmapDecoder jpeg = new JpegBitmapDecoder(st, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
  using (Stream stm = File.Create(fileName))
   JpegBitmapEncoder encoder = new JpegBitmapEncoder();
 catch (Exception exp)

The image will be generated via a WPF class but there are some really important issues that I encountered during this development proccess. When using canvas controls, you must Measure and Arrange the canvas before using it to render the image. If you do not do this you might get a blank canvas.

Bellow is the code need to render a image in the WPF project.

public Byte[] RenderImage(string passedInVar)



TextBlock tb = new TextBlock();

tb.Width = (double)400;

tb.Height = (double)200;

tb.TextAlignment = TextAlignment.Center;

tb.Text = "Text added via code...";

tb.FontSize = (Double)30;

tb.Foreground = Brushes.Blue;


//When adding children you might need to update the layout for controls...



//NB : You have to force the canvas to reload for it to

//re-render correctly when calling in from another source

Canvas canvas = (Canvas)this.FindName("InnerCanvas");

canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height));

canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height)));

int Height = ((int)(InnerCanvas.ActualHeight));

int Width = ((int)(InnerCanvas.ActualWidth));

RenderTargetBitmap rtb = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Pbgra32);


JpegBitmapEncoder jpg = new JpegBitmapEncoder();


Byte[] tmpArry;

using (MemoryStream ms = new MemoryStream())



tmpArry = ms.ToArray();


///NB : You need to clean up the thread manually

///as they will still reside in memory if they are not flagged 

///for termination....Thread count will go through the roof on

///the server if you dont invoke the following calls. 

if (jpg.Dispatcher.Thread.IsAlive)




if (rtb.Dispatcher.Thread.IsAlive)





jpg = null;

rtb = null;

return tmpArry;


Points of Interest

Threading in WPF created real havoc on our servers for some reason because, if you call a WPF application in a non-conventional way, it leaves running threads on the server. So be very careful when opening certain controls.

Make sure that the following is called when using any object that uses dispatchers.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Program Manager
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

GeneralThe calling thread cannot access this object because a different thread owns it. Pin
santhosh070523-Feb-10 23:28
Membersanthosh070523-Feb-10 23:28 
GeneralRe: The calling thread cannot access this object because a different thread owns it. Pin
Tarun.K.S14-Mar-11 1:16
MemberTarun.K.S14-Mar-11 1:16 
GeneralExample code is rather bloated... Pin
RandomEngy4-May-09 9:24
MemberRandomEngy4-May-09 9:24 
GeneralRe: Example code is rather bloated... Pin
Drazzing4-May-09 22:34
MemberDrazzing4-May-09 22:34 
RantSpeggeti code Pin
Bishoy Demian3-May-09 22:31
MemberBishoy Demian3-May-09 22:31 
QuestionIs this really such a good idea? Pin
Roger Alsing14-Oct-08 0:47
MemberRoger Alsing14-Oct-08 0:47 
AnswerRe: Is this really such a good idea? Pin
Drazzing14-Oct-08 1:11
MemberDrazzing14-Oct-08 1:11 
GeneralRe: Is this really such a good idea? Pin
Roger Alsing14-Oct-08 2:35
MemberRoger Alsing14-Oct-08 2:35 
GeneralRe: Is this really such a good idea? Pin
Drazzing14-Oct-08 3:13
MemberDrazzing14-Oct-08 3:13 
AnswerRe: Is this really such a good idea? Pin
Alois Kraus14-Oct-08 4:57
MemberAlois Kraus14-Oct-08 4:57 
GeneralRe: Is this really such a good idea? Pin
Drazzing14-Oct-08 23:09
MemberDrazzing14-Oct-08 23:09 
GeneralRe: Is this really such a good idea? Pin
scolemann17-May-09 11:49
Memberscolemann17-May-09 11:49 
General[Message Removed] Pin
hankjmatt13-Oct-08 23:48
Memberhankjmatt13-Oct-08 23:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.