This tutorial will demonstrate how to rotate images in an ASP.NET Web Site using C#.

Adding the Image

To demonstrate rotating images on a web page, we will need to create a simple website. At this point in the tutorial I have created a new ASP.NET Empty Web Site. Next, we will need to add an image to our project that we will use to display and rotate. For this I have created a sample image, but you can use any image you want to. To add it to the project:

  1. Right click the project in your Solution Explorer.
  2. Select Add Existing Item…
  3. Select the Image file you want to add.
  4. Click Add.

Adding the Default.aspx Page

What we need to do now is add in a Web Form with an image control and a button on it that we will use to view and rotate our image. To do this:

  1. Right click the project in your Solution Explorer.
  2. Select Add New Item…
  3. Select a Web Form.
  4. Name it Default.aspx.
  5. Click Add.
  6. Open Default.aspx up to Design mode.
  7. Drag and drop an Image Control onto the Web Form.
  8. In the Properties window, modify the Image Control’s ImageUrl property by selecting the ‘…’ button and choosing the image that we added to the project. In this case I have named mine tmpImage.gif and the ImageUrl is “~/tmpImage.gif”.
  9. Add a line break after the Image Control.
  10. Drag and drop a Button Control underneath the Image Control.

Rotating the Image

Next, we need to add in some C# code that will actually rotate our image. What we are going to do here is load the image into memory, rotate it, and then overwrite the old image by saving the new rotated image in its place. Furthermore, we will want this functionality to take place when the button we added earlier is clicked. To do this:

  1. Double click the Button Control we added earlier to generate the button click event method and open the Default.aspx.cs code behind file for editing.
  2. At the top of the class we need to add the following using statement:

  3. In the Button1_Click event method that was generated we need to add the following code:

Let’s review what this code is doing. First, we get the path to the image relative to our server and set that into a string named ‘path’. We then create an Image object in memory that we will use to modify the image. We then call the built in rotate method, passing the parameter by which you want the image rotated. We then save the image and release the file once we are done working with it.


To test this out and ensure that it is working, simply load up the web site and click the button to ensure the image is rotating. My image looks like this:

 Then when the button is clicked ->

The Default.aspx source looks like this:

Download Source Files