To read the article online, visit http://www.4GuysFromRolla.com/webtech/090201-1.shtml

Drawing Serpinski's Triangle with ASP.NET

By Scott Mitchell


Introduction
One of the cool things that ASP.NET developers now have at their disposal is the ability to create images on the fly and either save these images to the Web server's file system or stream these images directly to the browser! In fact, in my latest coauthored book - ASP.NET: Tips, Tutorials, and Code - I present an ASP.NET Web page that generates a bar chart on the fly from database data.

There will eventually be some articles on 4Guys that show very practical uses of creating on-the-fly images through an ASP.NET Web page, but for now, let's look at some cool things we can do with: specifically, creating a fractal. "What is a fractal?" Glad you asked. According to Dictionary.com, a fractal is a "geometric pattern that is repeated at ever smaller scales to produce irregular shapes and surfaces that cannot be represented by classical geometry." The fractal we are going to create is a famous, well-known one called Serpinski's Triangle - it's well-known because it's quite easy to implement!

The Serpinski Triangle Explained
You can read a very technical description of Serpkinski's Triangle (and a bit on other fractals, and classes of fractals), here. The short version for creating Serpkinski's Triangle goes something like this:

  1. Create a triangle, labelling each point of the triangle as P1, P2, and P3.
  2. Pick a point within the triangle, call that CurrentPoint.
  3. Now, randomly choose a number between 1 and 3.
  4. If the value is 1, move CurrentPoint to the mid-point of the line between CurrentPoint and P1.
  5. If the value is 2, move CurrentPoint to the mid-point of the line between CurrentPoint and P2.
  6. If the value is 3, move CurrentPoint to the mid-point of the line between CurrentPoint and P3.
  7. Mark the paper (or draw a pixel, or whatever) at the new CurrentPoint.
  8. Return to Step 3.

Serpinski's Traingle with 10,000 iterations. These steps can be repeated however many times you like. The more times they are repeated, the sharper the image will come in. The image to the right is a Serpinski Triangle generated from the C# code we will examine shortly, with 10,000 iterations. Note that the image appears to have triangles inside triangles inside triangles inside ... well, you get the point. The fact of the matter is that if you were to zoom into any region of Serpinski's Triangle you would find the base pattern (triangles inside triangles inside...) repeated ad infinitum.

Creating Images via an ASP.NET Web Page
ASP.NET Web pages can utilize all of the classes within the .NET Framework. This framework of classes contains a plethora of methods and properties that cover an amazing array of tasks. One such group of classes can be found in the System.Drawing namespace; these classes, as the namespace indicated, serve as a means to create images. From our ASP.NET Web page, we can use these classes to create an in-memory image and then either save the file to the Web server's file system or stream it directly to the browser.

To create an image in ASP.NET the first thing we have to do is import the System.Drawing and System.Drawing.Imaging namespaces:

<% @Import Namespace="System.Drawing" %>
<% @Import Namespace="System.Drawing.Imaging" %>

To create an image, the first step is to create an instance of the Bitmap class, specifying the size of the image you'd like to create. Once we create an instance of the Bitmap class, we can either use the Bitmap classes rudamentary SetPixel method to draw an image, a pixel at a time, or we can create an instance of the Graphics class, which has methods for drawing lines, arcs, ellipses, rectangles, curves, polygons, text, etc. Since the Serpinski Triangle algorithm only requires that a single point be put down (many times), we'll not use the Graphics class here, but I highly suggest you check it out. If you have the .NET Framework docs installed locally, you can read about the Graphics class at: ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemDrawingGraphicsClassTopic.htm.

So, to create Serpinski's Triangle in an ASP.NET Web page, we'll start by creating a function named Serpinski that takes three parameters: the width of the image to create, the height, and the number of iterations we wish to perform:

<% @Import Namespace="System.Drawing" %>
<% @Import Namespace="System.Drawing.Imaging" %>
<script language="c#" runat="server">

  void Serpinski(int width, int height, int iterations)
  {

The first step we need to accomplish is to create a properly-sized instance of the Bitmap class. We can accomplish this in the following line of code:

    // create the Bitmap
    Bitmap bitmap = new Bitmap(width, height);

At this point, we're ready to begin our Serpinski's Triangle algorithm. We need to first create our three triangle points and our current point. To do this, we'll create instances of the Point class, which can be used to help conceptualize a two-dimensional point. Also, we'll start our current point in the middle of the triangle:

    // Create our triangle's three Points
    Point top = new Point(width / 2, 0),
          bottomLeft = new Point(0,height),
          bottomRight = new Point(width, height);

    // Now, choose our starting point
    Point current = new Point(width / 2, height / 2);

Now comes the real work of the algorithm. We must perform iteration number of iterations. With each iteration, we need to pick a random number between 1 and 3 (we'll actually choose a random number between 0 and 2), and then, based on that number, adjust our point. The whole while, we'll need to color the pixel at the position of the current point (current). We'll color a pixel by using the SetPixel method of the Bitmap class, which takes three input paramteres: the x and y positions, and the color. The resulting code is pretty striaghtforward:

    // Iterate iterations times
    Random rnd = new Random();
    for (int iLoop = 0; iLoop < iterations; iLoop++)
    {
       // draw the pixel
       bitmap.SetPixel(current.X, current.Y, Color.Red);

       // Choose our next pixel
       switch (rnd.Next(3))
       {
          case 0:
             current.X -= (current.X - top.X) / 2;
             current.Y -= (current.Y - top.Y) / 2;
             break;

          case 1:
             current.X -= (current.X - bottomLeft.X) / 2;
             current.Y -= (current.Y - bottomLeft.Y) / 2;
             break;

          case 2:
             current.X -= (current.X - bottomRight.X) / 2;
             current.Y -= (current.Y - bottomRight.Y) / 2;
             break;
       }
    }

At this point, we have our image drawn. All that remains is to either save it to the Web server's file system, or stream it directly to the user's browser. To do either, use the Save method of the Bitmap class. If you want to save it to a file, use:

bitmapClassInstance.Save(filename, ImageFormat);

And if you want to stream it to the client's browser use:

bitmapClassInstance.Save(Response.OutputStream, ImageFormat);

Of course, if you're going to stream it directly to the client's browser, you should set the ContentType property of the Response object to the proper MIME type. (This MIME type would depend on the ImageFormat you chose to use.) The second parameter, ImageFormat needs to be an instance of the ImageFormat class; this class contains several static properties for common image types, such as: ImageFormat.Jpeg, ImageFormat.Gif, ImageFormat.Bmp, etc. So, in our example, let's stream the image to the client's browser as a Jpeg file.

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

That's all we have to do! At this point, we should just clean up and end our function:

    // clean up...
    bitmap.Dispose();
  }

We can now call this function from the Page_Load event handler, specifying the size of the image and how many iterations to perform. The Serpinski's Triangle image shown earlier in this article was created with the following Page_Load event handler code:

  void Page_Load(Object senter, EventArgs e)
  {
    Serpinski(200, 200, 10000);
  }

Conclusion
Drawing images via an ASP.NET Web page is fairly simple and straightforward. While we didn't examine the Graphics class, there you'll find a rich array of methods to accomplish nearly any drawing function you'll ever require. (Be sure to read up on that class!) Also, we can either save our images to the Web server's filesystem, or stream them directly to the client's browser. Neat, neat stuff. (For more information on ASP.NET be sure to check out the ASP.NET Article Index.)

Happy Programming!

  • By Scott Mitchell


    Attachments:

  • Download the complete code (in text format)
  • Visit the ASP.NET Article Index


  • Article Information
    Article Title: Drawing Serpinski's Triangle with ASP.NET
    Article Author: Scott Mitchell
    Published Date: Sunday, September 02, 2001
    Article URL: http://www.4GuysFromRolla.com/webtech/090201-1.shtml


    Copyright 2014 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers