Generally we were required, in our classic ASP applications, to generate thumbnail
images by using a 3rd party COM component. To do the same in the .NET
Framework, you need not depend any more on those tools. It has built in
functionality which will convert an original image to a thumbnail without ever
writing a physical file to the hard disk. Of course, you have the option to save the result if you want.
It will allow users to specify the width and height of the thumbnail image using
a QueryString
. It handles exceptions
by throwing an image not found, in case
you give a bad filename or invalid parameters. This code can be written within
an aspx page, there is no need to use code behind.
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim originalimg, thumb As System.Drawing.Image
Dim FileName As String
Dim inp As New IntPtr()
Dim width, height As Integer
Dim rootpath As String
rootpath = Server.MapPath("/")
FileName = rootpath & Request.QueryString("FileName")
Try
originalimg = originalimg.FromFile(FileName)
Catch
originalimg = originalimg.FromFile(rootpath & "error.gif")
End Try
If Request.QueryString("width") = Nothing Then
width = originalimg.Width
ElseIf Request.QueryString("width") = 0 Then
width = 100
Else
width = Request.QueryString("width")
End If
If Request.QueryString("height") = Nothing Then
height = originalimg.Height
ElseIf Request.QueryString("height") = 0 Then
height = 100
Else
height = Request.QueryString("height")
End If
thumb = originalimg.GetThumbnailImage(width, height, Nothing, inp)
Response.ContentType = "image/jpeg"
thumb.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)
originalimg.Dispose()
thumb.Dispose()
End Sub
</script>
Usage
http://<servername>/thumbnailimage.aspx?filename=<filename>&width=75&height=75
Where filename
should be path relative to the root of the application folder.
width
& height
are optional. If not specified, then the original width and height will be used.
If width
or height
are specified as 0, then the default width
/ height
of 100 pixels is used.
Examples
http://localhost/thumbnailimage.aspx?filename=win2000.gif
http://localhost/thumbnailimage.aspx?filename=win2000.gif&width=0&height=0
http://localhost/thumbnailimage.aspx?filename=win2000.gif&width=50&height=50
http://localhost/test/thumbnailimage.aspx?filename=test/win2000.gif
Notes
By default the thumbnail image generated is of type JPEG. One can change the
Response.Type
by changing the following code.
Response.ContentType = "image/jpeg"
thumb.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)
with the required supported format(Gif, Png, Bmp etc).