Click here to Skip to main content
15,885,910 members
Articles / Web Development / ASP.NET

A Simple Image Handler

Rate me:
Please Sign up or sign in to vote.
4.25/5 (8 votes)
14 May 2008CPOL3 min read 70K   2.4K   47  
An ASP.NET Handler for resizing and rotating/flipping images dynamically.
<%@ WebHandler Language="VB" Class="ImageHandlerVB" %>

Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Web
Imports System.Web.Caching

Public Class ImageHandlerVB : Implements IHttpHandler
    Public _width As Integer
    Public _height As Integer
    Public Shared noImageUrl As String = "images\no_photo.jpg"
    Public imageURL As String
    
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim bitOutput As Bitmap
        
        If context.Cache(("ImageQueryURL-" + context.Request.QueryString.ToString())) IsNot Nothing Then
            bitOutput = DirectCast(context.Cache(("ImageQueryURL-" + context.Request.QueryString.ToString())), Bitmap)
        Else
            Dim bitInput As Bitmap = GetImage(context)
            
            bitInput = RotateFlipImage(context, bitInput)
            
            If SetHeightWidth(context, bitInput) Then
                bitOutput = ResizeImage(bitInput, _width, _height)
            Else
                bitOutput = bitInput
            End If
            
            context.Response.ContentType = "image/jpeg"
            bitOutput.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
            
            context.Cache.Insert(("ImageQueryURL-" + context.Request.QueryString.ToString()), bitOutput, New CacheDependency(imageURL), Cache.NoAbsoluteExpiration, TimeSpan.FromHours(8), System.Web.Caching.CacheItemPriority.BelowNormal, _
             Nothing)
        End If
        
        context.Response.ContentType = "image/jpeg"
        bitOutput.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
        Return
    End Sub
    
    
    ''' <summary>
    ''' Get the image requested via the query string. 
    ''' </summary>
    ''' <param name="context"></param>
    ''' <returns>Return the requested image or the "no image" default if it does not exist.</returns>
    Public Function GetImage(ByVal context As HttpContext) As Bitmap
        If context.Cache(("ImagePath-" + context.Request.QueryString("image"))) Is Nothing Then
            Dim appPath As String = context.Server.MapPath(context.Request.ApplicationPath) + Path.DirectorySeparatorChar
            
            If [String].IsNullOrEmpty(context.Request.QueryString("image")) Then
                appPath += noImageUrl
            Else
                If System.IO.File.Exists((appPath + context.Request.QueryString("image"))) Then
                    appPath += context.Request.QueryString("image")
                Else
                    appPath += noImageUrl
                End If
            End If
            
            Dim bitOutput As Bitmap
            imageURL = appPath
            
            
            bitOutput = New Bitmap(appPath)
            context.Cache.Insert(("ImagePath-" + context.Request.QueryString("image")), bitOutput, New CacheDependency(imageURL), Cache.NoAbsoluteExpiration, TimeSpan.FromHours(8), System.Web.Caching.CacheItemPriority.BelowNormal, _
             Nothing)
            Return bitOutput
        Else
            Return DirectCast(context.Cache(("ImagePath-" + context.Request.QueryString("image"))), Bitmap)
        End If
    End Function
    
    
    ''' <summary>
    ''' Set the height and width of the handler class.
    ''' </summary>
    ''' <param name="context">The context to get the query string parameters, typically current context.</param>
    ''' <param name="bitInput">The bitmap that determines the </param>
    ''' <returns>True if image needs to be resized, false if original dimensions can be kept.</returns>
    Public Function SetHeightWidth(ByVal context As HttpContext, ByVal bitInput As Bitmap) As Boolean
        Dim inputRatio As Double = Convert.ToDouble(bitInput.Width) / Convert.ToDouble(bitInput.Height)
        
        If Not ([String].IsNullOrEmpty(context.Request("width"))) AndAlso Not ([String].IsNullOrEmpty(context.Request("height"))) Then
            _width = Int32.Parse(context.Request("width"))
            _height = Int32.Parse(context.Request("height"))
            Return True
        ElseIf Not ([String].IsNullOrEmpty(context.Request("width"))) Then
            _width = Int32.Parse(context.Request("width"))
            _height = Convert.ToInt32((_width / inputRatio))
            Return True
        ElseIf Not ([String].IsNullOrEmpty(context.Request("height"))) Then
            _height = Int32.Parse(context.Request("height"))
            _width = Convert.ToInt32((_height * inputRatio))
            Return True
        Else
            _height = bitInput.Height
            _width = bitInput.Width
            Return False
        End If
    End Function
    
    ''' <summary>
    ''' Flip or rotate the bitmap according to the query string parameters.
    ''' </summary>
    ''' <param name="context">The context of the query string parameters.</param>
    ''' <param name="bitInput">The bitmap to be flipped or rotated.</param>
    ''' <returns>The bitmap after it has been flipped or rotated.</returns>
    Public Function RotateFlipImage(ByVal context As HttpContext, ByVal bitInput As Bitmap) As Bitmap
        Dim bitOut As Bitmap = bitInput
        
        If [String].IsNullOrEmpty(context.Request("RotateFlip")) Then
            Return bitInput
        ElseIf context.Request("RotateFlip") = "Rotate180flipnone" Then
            bitOut.RotateFlip(RotateFlipType.Rotate180FlipNone)
        ElseIf context.Request("RotateFlip") = "Rotate180flipx" Then
            bitOut.RotateFlip(RotateFlipType.Rotate180FlipX)
        ElseIf context.Request("RotateFlip") = "Rotate180flipxy" Then
            bitOut.RotateFlip(RotateFlipType.Rotate180FlipXY)
        ElseIf context.Request("RotateFlip") = "Rotate180flipy" Then
            bitOut.RotateFlip(RotateFlipType.Rotate180FlipY)
        ElseIf context.Request("RotateFlip") = "Rotate270flipnone" Then
            bitOut.RotateFlip(RotateFlipType.Rotate270FlipNone)
        ElseIf context.Request("RotateFlip") = "Rotate270flipx" Then
            bitOut.RotateFlip(RotateFlipType.Rotate270FlipX)
        ElseIf context.Request("RotateFlip") = "Rotate270FlipXY" Then
            bitOut.RotateFlip(RotateFlipType.Rotate270FlipXY)
        ElseIf context.Request("RotateFlip") = "Rotate270FlipY" Then
            bitOut.RotateFlip(RotateFlipType.Rotate270FlipY)
        ElseIf context.Request("RotateFlip") = "Rotate90FlipNone" Then
            bitOut.RotateFlip(RotateFlipType.Rotate90FlipNone)
        ElseIf context.Request("RotateFlip") = "Rotate90FlipX" Then
            bitOut.RotateFlip(RotateFlipType.Rotate90FlipX)
        ElseIf context.Request("RotateFlip") = "Rotate90FlipXY" Then
            bitOut.RotateFlip(RotateFlipType.Rotate90FlipXY)
        ElseIf context.Request("RotateFlip") = "Rotate90FlipY" Then
            bitOut.RotateFlip(RotateFlipType.Rotate90FlipY)
        ElseIf context.Request("RotateFlip") = "RotateNoneFlipX" Then
            bitOut.RotateFlip(RotateFlipType.RotateNoneFlipX)
        ElseIf context.Request("RotateFlip") = "RotateNoneFlipXY" Then
            bitOut.RotateFlip(RotateFlipType.RotateNoneFlipXY)
        ElseIf context.Request("RotateFlip") = "RotateNoneFlipY" Then
            bitOut.RotateFlip(RotateFlipType.RotateNoneFlipY)
        Else
            Return bitInput
        End If
        
        Return bitOut
    End Function
    
    
    ''' <summary>
    ''' Resizes bitmap using high quality algorithms.
    ''' </summary>
    ''' <param name="originalBitmap"></param>
    ''' <param name="newWidth">The width of the returned bitmap.</param>
    ''' <param name="newHeight">The height of the returned bitmap.</param>
    ''' <returns>Resized bitmap.</returns>
    Public Shared Function ResizeImage(ByVal originalBitmap As Bitmap, ByVal newWidth As Integer, ByVal newHeight As Integer) As Bitmap
        Dim inputBitmap As Bitmap = originalBitmap
        Dim resizedBitmap As New Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb)
        
        Dim g As Graphics = Graphics.FromImage(resizedBitmap)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
        Dim rectangle As New Rectangle(0, 0, newWidth, newHeight)
        g.DrawImage(inputBitmap, rectangle, 0, 0, inputBitmap.Width, inputBitmap.Height, _
         GraphicsUnit.Pixel)
        g.Dispose()
        
        Return resizedBitmap
    End Function
    
    
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return True
        End Get
    End Property
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Arroweye Solutions
United States United States
I am a .net software developer based out of Chicago.

Comments and Discussions