C#将位图旋转90度

时间:2010-02-08 22:27:58

标签: c# bitmap

我正在尝试使用以下功能将位图旋转90度。问题在于,当高度和宽度不相等时,它会切断部分图像。

注意returnBitmap width = original.height,它的高度= original.width

任何人都可以帮我解决这个问题或指出我做错了什么吗?

    private Bitmap rotateImage90(Bitmap b)
    {
        Bitmap returnBitmap = new Bitmap(b.Height, b.Width);
        Graphics g = Graphics.FromImage(returnBitmap);
        g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
        g.RotateTransform(90);
        g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
        g.DrawImage(b, new Point(0, 0));
        return returnBitmap;
    }

3 个答案:

答案 0 :(得分:92)

this

怎么样?
private void RotateAndSaveImage(String input, String output)
{
    //create an object that we can use to examine an image file
    using (Image img = Image.FromFile(input))
    {
        //rotate the picture by 90 degrees and re-save the picture as a Jpeg
        img.RotateFlip(RotateFlipType.Rotate90FlipNone);
        img.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
}

答案 1 :(得分:9)

该错误是您第一次致电TranslateTransform

g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);

此转换需要位于returnBitmap而不是b的坐标空间中,因此应该是:

g.TranslateTransform((float)b.Height / 2, (float)b.Width / 2);

或等效

g.TranslateTransform((float)returnBitmap.Width / 2, (float)returnBitmap.Height / 2);

您的第二个TranslateTransform是正确的,因为它将在轮换之前应用。

然而,正如Rubens Farias建议的那样,使用更简单的RotateFlip方法可能会更好。

答案 2 :(得分:2)

我遇到了一点修改,我得到了它的工作。我发现了一些其他的例子,并注意到一些缺失对我有所帮助。我不得不调用SetResolution,如果我没有把图像调到错误的大小。我也注意到高度和宽度是向后的,尽管我认为无论如何都会对非方形图像进行一些修改。我想我会把这个发布给任何碰到过这个的人,就像我遇到同样的问题一样。

这是我的代码

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);
    }
}
相关问题