ASP.NET makes managing uploaded images and creating thumbnails relatively straightforward. I have utilized the following process to accept an uploaded image, and resize it to a maximum size of 200×200 pixels.
HTML
In order to receive an uploaded file, you only need a single server control, which will produce a textbox with a ‘Browse…’ button.
<input type="file" id="FileInput" runat="server" />
Code-Behind
Once the page is created, the code-behind has to handle the image from the postback and save it accordingly. The following code accepts an uploaded image, converts it to a maximum of a 200×200 pixel thumbnail, and saves it to the server.
Dim imgStream As System.IO.Stream
Dim imgPhoto As System.Drawing.Image
'Capture the image's stream
imgStream = Me.FileInput.PostedFile.InputStream
'Create an image (which we will manipulate) based on the stream
imgPhoto = System.Drawing.Image.FromStream(imgStream)
'The image must fit within a 200x200 pixel box
Const maxHeight As Integer = 200
Const maxWidth As Integer = 200
Dim imgHeight As Integer = imgPhoto.Height
Dim imgWidth As Integer = imgPhoto.Width
Dim imgScaleFactor As Double = 1
If imgHeight > maxHeight Then
imgScaleFactor = maxHeight / imgHeight
End If
If (imgWidth > maxWidth) And (maxWidth / imgWidth < imgScaleFactor) Then
'The image is wider than it is tall
imgScaleFactor = maxWidth / imgWidth
End If
'Resize the image based on the calculated scale factor
imgPhoto = imgPhoto.GetThumbnailImage(imgWidth * imgScaleFactor, imgHeight * _
imgScaleFactor, Nothing, Nothing)
Dim extension As String, fileName As String
fileName = Me.FileInput.PostedFile.FileName
'Retrieve the extension of the uploaded file
extension = Mid(fileName, InStrRev(fileName, ".") + 1, fileName.Length)
'Save the file to the server
'Note: you'll want to change the path and image name
imgPhoto.Save(Server.MapPath("/images/img." & extension))
Resizing the image
The imgScaleFactor variable is very important. The scale factor indicates the percent that the image needs to be reduced in order to fit in a 200×200 box. If the image is wider than it is tall, then imgScaleFactor will be based on the image’s width (and vice versa for a taller image). If the image fits inside a 200×200 box, then no resizing is needed.
A few caveats…
March 24th, 2008 at 9:38 am
Interesting page!, man
[Reply]