I need to rotate a JPEG image 90 degrees, and unfortunately the file that results from System.Drawing.Image.RotateFlip is not compatible with my end program. As an alternative, therefore, I am trying to use Graphics.RotateTransform. The current code seems like it should work, but the image gets clipped when it is rotated.
This is the image that I am using for testing.
Here is the code I am using to rotate the image:
Public Shared Sub ProcessJpeg()
Dim filePath As String = "C:\test.JPG"
Dim img As Bitmap = Nothing
img = New Bitmap(filePath)
img = RotateImage(img, 90.0F)
img.Save(Replace(filePath, ".JPG", "_new.JPG"))
End Sub
Shared Function RotateImage(b As Bitmap, angle As Single) As Bitmap
'create a new empty bitmap to hold rotated image
Dim returnBitmap As New Bitmap(b.Width, b.Height)
'make a graphics object from the empty bitmap
Dim g As Graphics = Graphics.FromImage(returnBitmap)
'move rotation point to center of image
g.TranslateTransform(CSng(b.Width) / 2, CSng(b.Height) / 2)
'rotate
g.RotateTransform(angle)
'move image back
g.TranslateTransform(-CSng(b.Width) / 2, -CSng(b.Height) / 2)
'draw passed in image onto graphics object
g.DrawImage(b, New Rectangle(New Point(0, 0), New Size(b.Width, b.Height)))
Return returnBitmap
End Function
The RotateImage function is from here.
I thought the solution was to simply reverse b.Width and b.Height on the third-to-last line of the RotateImage function, but that just makes matters worse.
Alternatively, if there is a better way to rotate a JPEG (apart from System.Drawing.Image.RotateFlip), I'd love to hear about it.