I have been attempting to rotate an Image and I have had some trouble with it. The first block of code was working, but it was causing an undesirable side effect: after the rotation, the Image was scaled down so that the x
dimension would match the preexisting y
dimension.
So I had the Image rotated, but it was only taking up part of the canvas.
In order to solve that, I figured I should just create a larger bitmap as an intermediate step, so that when it was rotated, the Image would not need to be shrunk in order to fit.
That code is in the second block. Unfortunately when I run it, I get a generic GDI error.
Anyone know what I've done wrong?
Works:
Imports System.Drawing
If XSize < YSize Then 'Needs to be rotated
Dim img As Image = Image.FromFile(strFilename)
Dim b = New Bitmap(img.Height, img.Width)
Dim gr As Graphics = Graphics.FromImage(b)
img.RotateFlip(RotateFlipType.Rotate90FlipNone)
gr.DrawImage(img, New Point(0, 0))
img = Nothing
b.Save(strFilename)
End If
This block of code does not work:
'Needs to be rotated
If XSize < YSize Then
Dim img As Image = Image.FromFile(strFilename)
Dim bmpTemp As Image
If img.Height > img.Width Then
bmpTemp = New Bitmap(img.Height, img.Height)
Else
bmpTemp = New Bitmap(img.Width, img.Width)
End If
Dim gr2 As Graphics = Graphics.FromImage(bmpTemp)
gr2.DrawImage(img, New Point(0, 0))
Dim b = New Bitmap(img.Height, img.Width)
Dim gr As Graphics = Graphics.FromImage(b)
bmpTemp.RotateFlip(RotateFlipType.Rotate90FlipNone)
gr.DrawImage(bmpTemp, New Point(0, 0))
img = Nothing
b.Save(strFilename)
End If
See Question&Answers more detail:os