Resizing images on the fly

The problem: A client uploads images to the server which could be either .jpg, .gif or .png files and will be of different dimensions.

They need to be displayed on the site no larger than 100px x 100px.

The solution: Using a simple .aspx script, it's possible to retrieve the height and width of each of the original uploaded images and then resize them proportionally to the size required on the site.

The script (saved as resize.aspx):

<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim objOriginal As System.Drawing.Image
Dim strFileName, strRootPath, imgSize, strImageSource As String
Dim inp As New IntPtr()
Dim intWidth, intHeight As Integer
imgSize = Request.Querystring("size")
strImageSource = "\image_folder\" & Request.Querystring("src")
objOriginal = objOriginal.FromFile(Server.Mappath(strImageSource))
If imgSize <> "" And IsNumeric(imgSize) Then
If objOriginal.Width >= objOriginal.Height Then
intWidth = CInt(imgSize)
If objOriginal.Width < intWidth Then
intWidth = objOriginal.Width
End If
IntHeight = CInt(imgSize)
If objOriginal.Height < intHeight Then
intHeight = objOriginal.Height
End If
End If
intWidth = objOriginal.Width
intHeight = objOriginal.Height
End If
If objOriginal.Width >= objOriginal.Height Then
If intWidth <> 0 Then
intHeight = objOriginal.Height/(objOriginal.Width/intWidth)
End If
If intHeight <> 0 Then
intWidth = objOriginal.Width/(objOriginal.Height/intHeight)
End If
End If
Dim originalFormat = objOriginal.rawformat
Dim objThumbnail As New Bitmap(objOriginal, intWidth, intHeight)
Dim imgResize As Graphics
imgResize = Graphics.FromImage(objThumbnail)
imgResize.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
imgResize.DrawImage(objOriginal, 0, 0, intWidth, intHeight)
If originalFormat.equals(System.Drawing.Imaging.ImageFormat.Jpeg) then
objThumbnail.Save(Response.Outputstream, originalFormat)
ElseIf originalFormat.equals(System.Drawing.Imaging.ImageFormat.Gif) then
objThumbnail.Save(Response.Outputstream, originalFormat)
ElseIf originalFormat.equals(System.Drawing.Imaging.ImageFormat.Png) then
Dim strMemStream As MemoryStream
strMemStream = new MemoryStream()
objThumbnail.Save(strMemStream, originalFormat)
Response.ContentType = "image/png"
End if
End Sub


Response.CacheControl = "no-cache"
Dim strImageFolderPath, fso, mainfolder, filecollection, file
strImageFolderPath = "d:\domains\\wwwroot\image_folder"
Set fso = CreateObject("Scripting.FileSystemObject")
Set mainfolder = fso.GetFolder(strImageFolderPath)
Set filecollection = mainfolder.Files

If filecollection.Count > 0 Then
For Each file In filecollection
<img src="resize.aspx?src=<%= %>&size=100" />
<% Next %>