Thursday, April 17, 2008

Create Thumbnail Image

Imports Microsoft.VisualBasic
Imports System.Drawing
Imports System.Drawing.Imaging

Public Class ThumbnailCreator

Public Shared Function CreateThumbnail(ByVal lcFilename As String, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As Bitmap

Dim bmpOut As System.Drawing.Bitmap = Nothing
Try

Dim loBMP As New Bitmap(lcFilename)

Dim loFormat As ImageFormat = loBMP.RawFormat

Dim lnRatio As Decimal

Dim lnNewWidth As Integer = 0

Dim lnNewHeight As Integer = 0

'If the image is smaller than a thumbnail just return it

If (loBMP.Width < lnWidth And loBMP.Height < lnHeight) Then
Return loBMP
End If

If (loBMP.Width > loBMP.Height) Then
lnRatio = CType((lnWidth / loBMP.Width), Decimal)
lnNewWidth = lnWidth

Dim lnTemp As Decimal = loBMP.Height * lnRatio
lnNewHeight = CInt(lnTemp)
Else
lnRatio = CType((lnHeight / loBMP.Height), Decimal)

lnNewHeight = lnHeight

Dim lnTemp As Decimal = loBMP.Width * lnRatio
lnNewWidth = CInt(lnTemp)
End If

bmpOut = New Bitmap(lnNewWidth, lnNewHeight)

Dim g As Graphics = Graphics.FromImage(bmpOut)

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic

g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight)

g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight)

loBMP.Dispose()


Catch
Return Nothing
End Try
Return bmpOut
End Function


End Class

No comments: