User-1969244055 posted
I have the following .ashx file which is an thumbnailer. It outputs the image to the response stream using the context object. To use it, do an image tag like
My problem is that the output quality of the thumbnail is shocking even though I've speicified the jpeg quality using EncoderParameters. What have I done wrong here?
<%@ WebHandler Language="vb" Class="Thumb" %> Imports System Imports System.IO Imports System.Web Imports System.Drawing Imports System.Drawing.Imaging Imports System.Configuration Public Class Thumb Implements IHttpHandler Public Function ThumbCallback()
As Boolean Return False End Function Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return True End Get End Property Private Function GetEncoderInfo(ByVal mimeType As String) As ImageCodecInfo Dim j As Integer Dim encoders
As ImageCodecInfo() encoders = ImageCodecInfo.GetImageEncoders() For j = 0 To encoders.Length If encoders(j).MimeType = mimeType Then Return encoders(j) End If Next j Return Nothing End Function Public Sub ProcessRequest(ByVal context As HttpContext) Implements
IHttpHandler.ProcessRequest Dim _W As Integer = 0 Dim _H As Integer = 0 Dim _oW As Integer = 0 Dim _oH As Integer = 0 Dim _F As Double = 0.0F Dim _fX As Double = 0.0F Dim _fY As Double = 0.0F Dim _width As Integer = 0 Dim _height As Integer = 0 Dim _quality
As Integer = 85 Dim _path As String = String.Empty If context.Request("src") Is Nothing Then Exit Sub ' Broken image Else _path = context.Request.MapPath(context.Request("src")) End If If Not context.Request("width") Is Nothing Then _width = Int32.Parse(context.Request("width"))
End If If Not context.Request("height") Is Nothing Then _height = Int32.Parse(context.Request("height")) End If If Not context.Request("quality") Is Nothing Then _quality = Int32.Parse(context.Request("quality")) End If Dim thumb As Bitmap = New Bitmap(_path)
_W = thumb.Width _H = thumb.Height if _width > 0 Then _fX = _W/_width if _height > 0 Then _fY = _H/_height If _fX > _fY Then _F = _fX Else _F = _fY End If If _F = 0 Then _F = 1 ' To stop Division by Zero If _F < 1 Then _F = 1 ' To stop small images being scaled
up _oW = _W / _F _oH = _H / _F context.Response.ContentType = "image/jpeg" Dim eps As EncoderParameters = New EncoderParameters(1) eps.Param(0) = New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, _quality) Dim ici As ImageCodecInfo = GetEncoderInfo("image/jpeg")
thumb = thumb.GetThumbnailImage(_oW, _oH, New Image.GetThumbnailImageAbort(AddressOf ThumbCallback), IntPtr.Zero) thumb.save(context.Response.OutputStream, ici, eps) End Sub End Class