Public Function rotate(ByVal img As Bitmap, ByVal angle As Single) As Bitmap
Dim pi2 As Double = PI / 2.0
Dim oldWidth As Double = img.Width
Dim oldHeight As Double = img.Height
Dim theta As Double = angle * PI / 180.0
Dim locked_theta As Double = theta
Dim newWidth, newHeight As Double
Dim nWidth, nHeight As Integer
Dim adjacentTop, oppositeTop As Double
Dim adjacentBottom, oppositeBottom As Double
If (locked_theta >= 0.0 And locked_theta < pi2) Or (locked_theta >= Math.PI And locked_theta < (Math.PI + pi2)) Then
adjacentTop = Math.Abs(Math.Cos(locked_theta)) * oldWidth
oppositeTop = Math.Abs(Math.Sin(locked_theta)) * oldWidth
adjacentBottom = Math.Abs(Math.Cos(locked_theta)) * oldHeight
oppositeBottom = Math.Abs(Math.Sin(locked_theta)) * oldHeight
Else
adjacentTop = Math.Abs(Math.Sin(locked_theta)) * oldHeight
oppositeTop = Math.Abs(Math.Cos(locked_theta)) * oldHeight
adjacentBottom = Math.Abs(Math.Sin(locked_theta)) * oldWidth
oppositeBottom = Math.Abs(Math.Cos(locked_theta)) * oldWidth
End If
newWidth = adjacentTop + oppositeBottom
newHeight = adjacentBottom + oppositeTop
nWidth = Math.Ceiling(newWidth)
nHeight = Math.Ceiling(newHeight)
Dim rotatedBmp As Bitmap = New Bitmap(nWidth, nHeight)
Dim g As Graphics = Graphics.FromImage(rotatedBmp)
Dim points(2) As Point
If locked_theta >= 0.0 And locked_theta < pi2 Then
points(0) = New Point(CInt(oppositeBottom), 0)
points(1) = New Point(nWidth, CInt(oppositeTop))
points(2) = New Point(0, CInt(adjacentBottom))
ElseIf locked_theta >= pi2 And locked_theta < Math.PI Then
points(0) = New Point(nWidth, CInt(oppositeTop))
points(1) = New Point(CInt(adjacentTop), nHeight)
points(2) = New Point(CInt(oppositeBottom), 0)
ElseIf locked_theta >= Math.PI And locked_theta < (Math.PI + pi2) Then
points(0) = New Point(CInt(adjacentTop), nHeight)
points(1) = New Point(0, CInt(adjacentBottom))
points(2) = New Point(nWidth, CInt(oppositeTop))
Else
points(0) = New Point(0, CInt(adjacentBottom))
points(1) = New Point(CInt(oppositeBottom), 0)
points(2) = New Point(CInt(adjacentTop), nHeight)
End If
g.DrawImage(img, points)
g.Dispose()
Return rotatedBmp
End Function