Friday 18 January 2008

Uploading Images and Creating Thumbnails

Import these NameSpaces in the code behind:

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

Let's say you have a FileUpload control called upImage and a Button called btnUpload on your aspx page. The subroutine for btnUpload would look like this:

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles btnUpdateProduct.Click

'upload image file
Dim savePath As String
savePath = Server.MapPath("/uploads/")
If Me.upImage.HasFile Then
Dim fileName As String
fileName = upImage.FileName

'***************************************
' remove spaces and non alphanumeric
'characters from image names
'***************************************
fileName = fileName.Replace(" ", "")
fileName = fileName.Replace("(", "")
fileName = fileName.Replace(")", "")
fileName = fileName.ToLower

savePath += fileName
upImage.SaveAs(savePath)


'****************************************************************
' resize and thumbnail uploaded image
'****************************************************************

Dim fullSizeImg As System.Drawing.Image
fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath("/uploads/" & fileName))

'Duplicate image to reasonable size
Dim h As Integer
h = fullSizeImg.Height
Dim w As Integer
w = fullSizeImg.Width
Dim nh As Integer
nh = h * 300 / w
Dim thumbNailImg1 As System.Drawing.Image
thumbNailImg1 = fullSizeImg.GetThumbnailImage(300, nh, dummyCallBack, IntPtr.Zero)

Dim nProdImg As String
nProdImg = "img" & fileName
thumbNailImg1.Save(Server.MapPath("/talkisgreen/img/phones/thumbs/" & nProdImg))
'Delete original file
TidyFile(fileName)
End Sub




Sub TidyFile(ByVal fileName As String)
Dim path As String
path = Server.MapPath("/uploads/")
Try
' Delete the newly created file.
File.Delete(path & fileName)
Catch e As Exception

End Try

End Sub



No comments: