May 11, 2005

Dynamics Graphics In ASP.Net

Use this to create a Dynamic graphics object
<img src="DynamicImage.aspx" border="1" alt="Dynamically Graphics Object">
where DynamicImage.aspx is:
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<script language="C#" runat="server">

void Page_Load(Object sender, EventArgs e)
{
  Bitmap bitmap = new Bitmap(200, 200);
  Graphics gfx = Graphics.FromImage(objBitmap);

  // use 'gfx' object to create graphics
  SolidBrush objBlackBrush = new SolidBrush(Color.Black),
             objYellowBrush = new SolidBrush(Color.Yellow);
  Font font = new Font("Arial Black", 9);


  gfx.FillRectangle(new SolidBrush(Color.Ivory),
                            0, 0, 200, 200);
  gfx.DrawString("Blah, blah, blah", font, objBlackBrush, 5, 8);
  gfx.FillEllipse(objYellowBrush, 375, 5, 50, 50);
  ...

  Response.ContentType = "image/jpeg";
  bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

  gfx.Dispose();
  bitmap.Dispose();
}
</script>
The trick here is to save the bitmap to the 'OutputStream'.

No comments: