Rendering Bitmaps
On-the-fly image manipulation is easy but has some significant performance costs. If you intend to use this technique on your web site, be sure to test the performance under load to determine if you can achieve your performance goals. Caching images in the ASP.NET cache may improve performance, but only if a small percentage of images and formatting options are requested a large percentage of the time. If your web site doesn't require dynamic image manipulation, you'll achieve much better performance by rendering your images in advance, and deploying the image files to your web site.
The web site project includes the console application PreRenderBitmap. Run this program in a Command prompt. If you run PreRenderBitmap without parameters, it displays a list of the parameters that it expects. The program has parameters for all of the formatting options that the ImageHandler accepts. PreRenderBitmap renders the image with the specified formatting, and then writes it to a .jpg file. If you use PreRenderBitmap to create all the bitmaps that your site displays, there's no need to use ImageHandler. Instead, you can rely on IIS to serve up images, or use the PreRenderedImageHandler. The PreRenderedImageHandler just checks to ensure that an image request is coming from your web site before it serves up the image. You'll need to change web.config to disable ImageHandler and enable PreRenderedImageHandler.
If your web site is hosted on a server that's shared by multiple companies, you may not have access to the IIS configuration to configure mappings for Http Handlers. If you're in this situation, you can use Generic Http Handlers, which require no IIS and no web.config configuration. To add a Generic Handler to your project, right-click the project, select Add New Item, and choose Generic Handler. Unlike Http Handlers that serve up content based on a file type, Generic Handlers are accessed by directly specifying them in URLs. For example, if you create a Generic Handler named "Handler.ashx," refer to it in a URL:
<img src="Handler.ashx?filename= Images/2004_03_06_17_51_46.jpg?q= 100&sx=0.5&sy=0.5 ..." />
The .NET Bitmap class plus Http Handlers make on-the-fly image generation simple. While caching images in the ASP.NET cache may improve performance, dynamic bitmap rendering has a high performance cost. Unless your web site requires dynamic image generation, you'll achieve optimal performance by rendering all images in advance and copying the image files to your web site. If you use an Http Handler to serve up images, remember to call Response.Cache.SetExpires to ensure that the image is cached on the client machine. After I set up my stock photography web site, you might start seeing my pictures in annoying advertisements littered all over your favorite web sites. I really hope so!