Home > Guides > Programming > .NET and Windows Programming

Toggle Open Guide Table of ContentsGuide Contents

Close Table of ContentsGuide Contents

Close Table of Contents

Returning an Image in a Web Page

Last updated Dec 16, 2004.

Some Web sites use scripts to serve up all content, even images and other static data. This allows them to more tightly control their content, and limits the number of URLs that are available on the Web site. For example, a picture that you would normally access by browsing to http://www.companyxyz.com/picture1.jpg, you would access instead by visiting http://www.companyxyz.com/picture.aspx?pic=picture1.

Using this technique for static content is most advantageous for companies that have Web sites with quickly changing content and who are concerned about the security ramifications of giving their content developers access to deploy files onto the server.

The technique is also very useful if you want to return a random picture, or a picture that's generated in response to parameters that the user enters on the query string or in a Web page.

Returning a Static Image

Returning a picture from an .aspx program isn't terribly difficult. All you have to do is load or create the picture in a .NET Image object and then write the contents of the Image to the output stream. For example, if you create an ASP.NET page that contains the Page_Load method shown here, it will select one of two different pictures and return it in the request stream:

[C#]

private void Page_Load(object sender, System.EventArgs e)
{
  // Get the current time.
  // If an odd second, return picture 1. On even seconds return picture 2.
  int ss = DateTime.Now.Second;

  // load the image
  using (System.Drawing.Image img = LoadImage(ss % 2))
  {
    // and return it as a JPEG file
    Response.ContentType = "image/jpeg";
    img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
  }
}

private System.Drawing.Image LoadImage(int imgNum)
{
  string imgName = Server.MapPath(string.Format("picture{0}.jpg", imgNum));
  Bitmap bmp = new Bitmap(imgName);
  return bmp;
}

[Visual Basic]

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  ' Get the current time.
  ' If an odd second, return picture 1. On even seconds return picture 2.
  Dim ss As Integer = DateTime.Now.Second

  ' load the image
  Dim img As System.Drawing.Image = LoadImage(ss Mod 2)
  Try
    Response.ContentType = "image/jpeg"
    img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
  Finally
    img.Dispose()
  End Try
End Sub

Function LoadImage(ByVal imgNum As Integer) As System.Drawing.Image
  Dim imgName As String = Server.MapPath(String.Format("picture{0}.jpg", imgNum))
  Dim bmp As New Bitmap(imgName)
  Return bmp
End Function

This code assumes that the pictures are stored in the application's default directory, so I used Server.MapPath to locate them. In a real application, you'd probably have the images stored in a directory that's not accessible from the outside, or in a database as I mentioned earlier. If you want to run this program, you'll have to place two images named picture0.jpg and picture1.jpg in the Web application's directory.

Note that I set the content type to "image/jpeg" before returning the picture. Although this isn't absolutely required, it's a good thing to identify the content type that you're returning.

Generating an Image Dynamically

Returning a dynamically generated image isn't any more difficult than returning an image that you loaded from the disk. Well, except for actually creating the image. You have to create a Bitmap object of the size that you want, draw on it, and then return the resulting image.

Here's a LoadImage method that shows how to do that. It will create a circle on even seconds (imgNum = 0), and a square on odd seconds (imgNum = 1).

[C#]

private System.Drawing.Image LoadImage(int imgNum)
{
  Bitmap bmp = new Bitmap(100, 100);
  using (Graphics g = Graphics.FromImage(bmp))
  {
    g.Clear(Color.White);
    if (imgNum == 0)
    {
      g.FillEllipse(Brushes.Blue, 0, 0, 100, 100);
    }
    else
    {
      g.FillRectangle(Brushes.Cyan, 0, 0, 100, 100);
    }
  }
  return bmp;
}

[Visual Basic]

Function LoadImage(ByVal imgNum As Integer) As System.Drawing.Image
  Dim bmp As New Bitmap(100, 100)
  Dim g As Graphics = Graphics.FromImage(bmp)
  Try
    g.Clear(Color.White)
    If imgNum = 0 Then
      g.FillEllipse(Brushes.Blue, 0, 0, 100, 100)
    Else
      g.FillRectangle(Brushes.Cyan, 0, 0, 100, 100)
    End If
  Finally
    g.Dispose()
  End Try
  Return bmp
End Function

You can replace the LoadImage method from the previous example with this code.

Of course, you can create any size image you like using this technique, and draw whatever you want in it. Once you've created the Bitmap object and created the Graphics object, you have access to all of the GDI+ drawing commands.

Discussions

Copies of the array?
Posted Dec 23, 2008 03:40 PM by luige21
1 Replies
Hi
Posted Dec 5, 2008 05:10 AM by ajay2000bhushan
2 Replies
You have no clue.
Posted Jun 10, 2008 03:28 PM by theinternetmaster
1 Replies

Make a New Comment

You must log in in order to post a comment.

Related Resources

Jim Mischel"Highly unlikely" does not mean "impossible"
By Jim MischelJuly 18, 2009 No Comments

One of my programs crashed the other day in a very unexpected place.  A call to System.Threading.ConcurrentQueue.TryDequeue (from the Parallel Extensions to .NET) resulted in an OverflowException being thrown.  Investigation revealed a pretty serious bug in the System.Random constructor.

It's Here; Put Away Your Pre-Conceptions on What an OS Must Be: Part II
By John TraenkenschuhMay 24, 2009 No Comments

In the last blog in this series, Traenk relates his first experiences with computers and with coding.  But now, some years have passed. . .

It's Here; Put Away Your Pre-Conceptions on What an OS Must Be: Part I
By John TraenkenschuhMay 24, 2009 No Comments

Traenk relates his past experience with Operating Systems that goes back 25 years, ok, more than that but he ain't tellin'

See More Blogs

Informit Network