Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Web

Public Class TiffPageHandler
    Implements IHttpHandler

    Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim fileName As String = context.Request.QueryString("file")
        Dim filePath As String = context.Server.MapPath("~/TiffFiles/" & fileName)

        If String.IsNullOrEmpty(fileName) OrElse Not IO.File.Exists(filePath) Then
            context.Response.StatusCode = 404
            context.Response.End()
            Return
        End If

        Using tiffImage As Image = Image.FromFile(filePath)

            Dim dimension As New FrameDimension(tiffImage.FrameDimensionsList(0))
            Dim pageCount As Integer = tiffImage.GetFrameCount(dimension)

            If context.Request.QueryString("count") = "1" Then
                context.Response.ContentType = "text/plain"
                context.Response.Write(pageCount.ToString())
                Return
            End If

            Dim pageIndex As Integer = 0
            Integer.TryParse(context.Request.QueryString("page"), pageIndex)

            If pageIndex < 0 Then pageIndex = 0
            If pageIndex >= pageCount Then pageIndex = pageCount - 1

            tiffImage.SelectActiveFrame(dimension, pageIndex)

            context.Response.ContentType = "image/png"
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
            tiffImage.Save(context.Response.OutputStream, ImageFormat.Png)

        End Using

    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class