Saturday, June 4, 2011

VB: Resize An Image While Maintaining Aspect Ratio and Maximum Height

This allows us to resize the image. It prevents skewed images and also vertically long images caused by trying to maintain the aspect ratio on images who's height is larger than their width

Source:


Public Sub ResizeImage(ByVal OriginalFile As String, ByVal NewFile As String, ByVal NewWidth As Integer, ByVal MaxHeight As Integer, ByVal OnlyResizeIfWider As Boolean)
Dim FullsizeImage As System.Drawing.Image = System.Drawing.Image.FromFile(OriginalFile)

' Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone)
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone)

If OnlyResizeIfWider Then
If FullsizeImage.Width <= NewWidth Then
NewWidth = FullsizeImage.Width
End If
End If

Dim NewHeight As Integer = FullsizeImage.Height * NewWidth \ FullsizeImage.Width
If NewHeight > MaxHeight Then
' Resize with height instead
NewWidth = FullsizeImage.Width * MaxHeight \ FullsizeImage.Height
NewHeight = MaxHeight
End If

Dim NewImage As System.Drawing.Image = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, Nothing, IntPtr.Zero)

' Clear handle to original file so that we can overwrite it if necessary
FullsizeImage.Dispose()

' Save resized picture
NewImage.Save(NewFile)
End Sub

No comments:

Post a Comment