C#将位图旋转90度

Kev*_*vin 49 c# bitmap

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

注意returnBitmap width = original.height,它的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;
    }
Run Code Online (Sandbox Code Playgroud)

Rub*_*ias 94

怎么样这个:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你不需要保存它; 那个'RotateFlip`就可以了.您可以删除`using`并添加`return new Bitmap(img);` (4认同)

fin*_*nnw 9

这个错误是你第一次打电话给TranslateTransform:

g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
Run Code Online (Sandbox Code Playgroud)

这个变换需要在坐标空间returnBitmap而不是b,所以这应该是:

g.TranslateTransform((float)b.Height / 2, (float)b.Width / 2);
Run Code Online (Sandbox Code Playgroud)

或者等价的

g.TranslateTransform((float)returnBitmap.Width / 2, (float)returnBitmap.Height / 2);
Run Code Online (Sandbox Code Playgroud)

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

然而RotateFlip,正如Rubens Farias建议的那样,你可能会用更简单的方法做得更好.