C# rotate bitmap 90 degrees

前端 未结 3 819
误落风尘
误落风尘 2020-12-03 06:10

I\'m trying to rotate a bitmap 90 degrees using the following function. The problem with it is that it cuts off part of the image when the height and width are not equal.

3条回答
  •  借酒劲吻你
    2020-12-03 06:52

    I came across and with a little modification I got it to work. I found some other examples and noticed something missing that made the difference for me. I had to call SetResolution, if I didn't the image ended up the wrong size. I also noticed the Height and Width were backwards, although I think there would be some modification for a non square image anyway. I figured I would post this for anyone who comes across this like I did with the same problem.

    Here is my code

    private static void RotateAndSaveImage(string input, string output, int angle)
    {
        //Open the source image and create the bitmap for the rotatated image
        using (Bitmap sourceImage = new Bitmap(input))
        using (Bitmap rotateImage = new Bitmap(sourceImage.Width, sourceImage.Height))
        {
            //Set the resolution for the rotation image
            rotateImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
            //Create a graphics object
            using (Graphics gdi = Graphics.FromImage(rotateImage))
            {
                //Rotate the image
                gdi.TranslateTransform((float)sourceImage.Width / 2, (float)sourceImage.Height / 2);
                gdi.RotateTransform(angle);
                gdi.TranslateTransform(-(float)sourceImage.Width / 2, -(float)sourceImage.Height / 2);
                gdi.DrawImage(sourceImage, new System.Drawing.Point(0, 0));
            }
    
            //Save to a file
            rotateImage.Save(output);
        }
    }
    

提交回复
热议问题