Generate Thumbnail - VB.Net
The following function allows the automatic creation of a thumbnail from an uploaded image. It is assumed that thumbnail is required (a check before the function is called).
Public Function GenerateThumbnail(ByVal sFullImagePath As String, ByVal sImageSavePath As String, ByVal sSaveName As String, ByVal iX As Integer, ByVal iY As Integer) As String
'Create a new image object
Dim imgFull As System.Drawing.Image
'Fill the imgFull object with uploaded image by it's file URL
imgFull = System.Drawing.Image.FromFile(sFullImagePath)
'Get the format of the uploaded image
Dim imgFormat = imgFull.RawFormat
'Store the original image sizes for use later
Dim iOrigWidth = imgFull.Width
Dim iOrigHeight = imgFull.Height
Dim iNewX As Integer
Dim iNewY As Integer
Dim iRatio As Decimal
'The radio is the required X value divided by the current X value
iRatio = iX / iOrigWidth
'Set the new values using the radio
iNewX = iOrigWidth * iRatio
iNewY = iOrigHeight * iRatio
'Create a new Bitmap object from the image and the sizes
Dim imgOutput As New Bitmap(imgFull, iNewX, iNewY)
'Create a Graphics object
Dim gfxResizer As Graphics
'Populate the object from the BMP
gfxResizer = Graphics.FromImage(imgOutput)
'Set the image to high quality so we dont loose anything when converted
gfxResizer.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gfxResizer.DrawImage(imgFull, 0, 0, iNewX, iNewY)
'Save the image to the filesystem
imgOutput.Save(sImageSavePath & "/" & sSaveName, imgFormat)
sSaveName = sSaveName
'Dispose of the created objects
gfxResizer.Dispose()
imgOutput.Dispose()
imgFull.Dispose()
'Return the filename
Return sSaveName
End Function