HttpHandler personalizzato

FILE Web.Config

 

<configuration>
   <system.web>
      <httpHandlers>
        <add path="*.jpg" verb="GET" type="NamespaceHttpHandler.ImageHandler, App_Code"/>
      </httpHandlers>
   </system.web>
</configuration>

 

Namespace NamespaceHttpHandeler

 

namespace NamespaceHttpHandeler {
 
   public class ImageHandlerFactory : IHttpHandlerFactory {
       
      IHttpHandler IHttpHandlerFactory.GetHandler(HttpContext context,
                     string requestType, string url, string pathTranslated) {
      
         // Guardo se è di mia competenza. Se fa parte delle immagini della cartella         
         // image utilizzo l’handler definito, altrimento passo all’Handler di default
         if (String.Compare(VirtualPathUtility.GetDirectory(context.Request.Path),
                          VirtualPathUtility.ToAbsolute("~/images/"), true) == 0)
            return new ImageHandler();
         else
            return new DefaultHttpHandler();
      }
 
      void IHttpHandlerFactory.ReleaseHandler(IHttpHandler handler){
      }
   }
 
   public class ImageHandler : IHttpHandler {
 
      private ImageCodecInfo      _jpegEncoder;
      private EncoderParameters   _jpegEncoderParams;
      private const int           margin = 5;
 
      bool IHttpHandler.IsReusable{ get { return true; } }
 
      void IHttpHandler.ProcessRequest(HttpContext context) {
           
         // Apro il file in lettura
         using (Stream stream = File.OpenRead(context.Request.PhysicalPath)) {
            // Carico l'immagine fisica
            using (Image image = Image.FromStream(stream)){
               // Ridimensiono l'immagine
               Image newImage = ResizeImageIfNeed(context, image);
 
               // Salvo l'immagine sul buffer di uscita
               context.Response.ContentType = MediaTypeNames.Image.Jpeg;
               context.Response.BufferOutput = false;
               newImage.Save(context.Response.OutputStream, JpegEncoder,
                              JpegEncoderParams);
            }
         }
      }
 
      private Image ResizeImageIfNeed(HttpContext context, Image image) {
           
         int width;
         int height;
 
         // Controllo i parametri di resize
         bool widthResize=Int32.TryParse(context.Request.QueryString["w"],out width);
         bool heightResize=Int32.TryParse(context.Request.QueryString["h"],out height);
 
         // Se non è stato richiesto nessun resize ritorno l'immagine originale
         if (!widthResize && !heightResize)
            return image;
         else if (widthResize && !heightResize){
            // Se è stato richiesto un resize sulla larghezza,
            // calcolo l'altezza proporzionalmente
            height = width * image.Height / image.Width;
         }
         else if (!widthResize && heightResize) {
            // Se è stato richiesto un resize sulla l'altezza,
            // calcolo la larghezza proporzionalm.
            width = height * image.Width / image.Height;
         }
 
         // Ritorno una nuova bitmap con le nuove dimensioni
         return new Bitmap(image, width, height);
      }
 
      private ImageCodecInfo JpegEncoder {
         get {
            if (_jpegEncoder == null)
               lock (this) {
                  if (_jpegEncoder == null) {
                     foreach (ImageCodecInfo codec in
                               ImageCodecInfo.GetImageEncoders())
                        if (String.Compare(codec.MimeType,
                                     MediaTypeNames.Image.Jpeg, true) == 0) {
                           _jpegEncoder = codec;
                           break;
                        }
                  }
               }
            return _jpegEncoder;
         }
      }
 
      private EncoderParameters JpegEncoderParams {
         get {
            if (_jpegEncoderParams == null)
               lock (this) {
                  if (_jpegEncoderParams == null) {
                     _jpegEncoderParams = new EncoderParameters(1);
                     _jpegEncoderParams.Param[0] = new
                     EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                  }
               }
            return _jpegEncoderParams;
         }
      }
   }
}