Working With Image in HttpHandler

This is the “HttpHandler and HttpModule in real scenerion” article series. As the name suggests, in this series we will understand a few real scenarios where we can use HttpHandler and HttpModule. In our previous two articles we have learned to implement simple HttpHandler in our ASP.NET application. You can read them here.

In this article we will work with images in HttpHandler. Here we can get a few realy helpful information uses of HttpHandler.

Generate Dynamic Image within HttpHandler

In this example we will generate an image dynamically, within HttpHandler. This situation may occur when you want to generate a dynamic image at runtime. For example, when a Captcha image is generated. Have a look at the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. namespace WebApp  
  9. {  
  10.     public class PictureHandler : IHttpHandler  
  11.     {  
  12.         public void ProcessRequest(HttpContext context)  
  13.         {  
  14.             int width = 200;  
  15.             int height = 200;  
  16.             Bitmap bitmap = new Bitmap(width, height);  
  17.             Graphics g = Graphics.FromImage((Image)bitmap);  
  18.             g.FillRectangle(Brushes.Red, 0f, 0f, bitmap.Width, bitmap.Height);  // fill the entire bitmap with a red rectangle  
  19.             MemoryStream mem = new MemoryStream();  
  20.             bitmap.Save(mem, ImageFormat.Png);  
  21.             byte[] buffer = mem.ToArray();  
  22.             context.Response.ContentType = "image/png";  
  23.             context.Response.BinaryWrite(buffer);  
  24.             context.Response.Flush();  
  25.         }   
  26.         public bool IsReusable  
  27.         {  
  28.             get  
  29.             {  
  30.                 return false;  
  31.             }  
  32.         }  
  33.     }  
  34. } 

If you have experience with the Drawing class in .NET then you can understand this example very quickly. Within the ProcessRequest() function we are generating an image with a specific height and width. Then we are setting this image within a memory stream and we are flashing it to an output stream.

Now, we need to register our custom PictureHandler in the web.config file. Here is the registration process.

  1. <system.webServer>  
  2.   <handlers>  
  3.       <add name="myImageHandler" verb="*" path="*.jpg" type="WebApp.PictureHandler"/>  
  4.    </handlers>  
  5. </system.webServer> 

Here is the output of above example.

Generate Dynamic Image within HttpHandler

Resize Image using HttpHandler

This is another implementation of HttpHandler. In this example we will resize an image dynamically. The concept is very similar to the previous concept, except that the image is from secondary storage. Have a look at the following example.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. namespace WebApp  
  8. {  
  9.     public class PictureHandler : IHttpHandler  
  10.     {  
  11.         public void ProcessRequest(HttpContext context)  
  12.         {  
  13.             //Get Height and width from Query string  
  14.             int Width = Int32.Parse(context.Request.QueryString["width"]);  
  15.             int Height = Int32.Parse(context.Request.QueryString["height"]);  
  16.             //Get Picture from Server  
  17.             string abc = context.Server.MapPath("~/Pic1.jpg");  
  18.             Image img = Image.FromFile(context.Server.MapPath("~/Pic1.jpg"));  
  19.             Image _img = new Bitmap(Height, Width);  
  20.             Graphics graphics = Graphics.FromImage(_img);  
  21.             //Resize picture according to size  
  22.             graphics.DrawImage(img, 0, 0, Width, Height);  
  23.             graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;  
  24.             graphics.Dispose();  
  25.             img.Dispose();  
  26.             //Create outpur sream  
  27.             MemoryStream str = new MemoryStream();  
  28.             _img = _img.GetThumbnailImage(Width, Height, null, IntPtr.Zero);  
  29.             _img.Save(str, System.Drawing.Imaging.ImageFormat.Png);  
  30.             _img.Dispose();  
  31.             str.WriteTo(context.Response.OutputStream);  
  32.             str.Dispose();  
  33.             str.Close();  
  34.             //Set response type  
  35.             context.Response.ContentType = ".jpg";  
  36.             context.Response.End();  
  37.         }  
  38.         public bool IsReusable  
  39.         {  
  40.             get  
  41.             {  
  42.                 return false;  
  43.             }  
  44.         }  
  45.     }  
  46. } 

In this example, we are resizing an image depending on height and width values in a query string. So if we want a different image then we need to supply a different value using a query string.

Here is the code to register the HttpHandler. If we request any image then our custom HttpHandler will execute.

  1. <handlers>  
  2.     <add name="myImageHandler" verb="*" path="*.jpg" type="WebApp.PictureHandler"/>  
  3. </handlers>

In this trial, we are passing a height and width value of 200 and we are getting an image of that size.

Resize Image using HttpHandler
Now, if we change the width value to 300 then the image size will change automatically.
 
change the width value to image size
Conclusion

In this article, we have learned how to work with HttpHandler in ASP.NET applications. I hope those examples will help you to understand some realistic scenarios where we can implement HttpHandler.

In a future article, we will focus on a few more concepts of HttpHandler.


Similar Articles