Wednesday, August 02, 2006

Creating thumbnail Image(VB.NET)

I wanted To Create a thumbnail Image from Original Picture And save it in Employee Data.I used image.GetThumbnailImage function to sort this out.So i thught to Publish it here ,it will be a Help for someone else.



' Photo path(Actual path to Uploaded Pic)

Public Shared Function CreateThumbnail(ByVal imagePath As String, ByVal Folder As String) As Boolean

Dim createdThumbnail As Boolean = False

Dim thumbnail As Image

Dim image As Bitmap



Try

' get full path to the thumbnail image

Dim thumbnailPath As String = Path.Combine(Folder, GetThumbnailName(imagePath))



' check thumbnail already exist

If Not File.Exists(thumbnailPath) Then

image = New Bitmap(imagePath)

' create thumbnail image

thumbnail =GetThumbnail(image, 120)



' save thumbnail

thumbnail.Save(thumbnailPath, ImageFormat.Jpeg)



createdThumbnail = True

End If

Catch ex As Exception

' an error occurred, return null

Finally

' clean up

If Not thumbnail Is Nothing Then thumbnail.Dispose()

If Not (image Is Nothing) Then image.Dispose()

End Try



Return createdThumbnail

End Function



Public Shared Function GetThumbnail(ByVal image As Bitmap, ByVal longestSide As Integer) As Image

Dim thumbnail As Image



Try

' determine scale of the image

Dim scale As Single = CSng(IIf(image.Width > image.Height, _

longestSide / image.Width, longestSide / image.Height))



Dim width As Integer = CInt(image.Width * scale)

Dim height As Integer = CInt(image.Height * scale)



thumbnail = image.GetThumbnailImage(width, height, Nothing, IntPtr.Zero)

Catch ex As Exception

' an error occurred, return null

End Try



Return thumbnail

End Function





Generated using PrettyCode.Encoder

1 comment:

Andrew Robinson said...

Thanks, I appreciate the code. I'll be putting it to good use.