2010-02-08 196 views
40

我想使用以下函数将位图旋转90度。它的问题在于,当高度和宽度不相等时,会切断图像的一部分。C#旋转位图90度

通知的returnBitmap宽度= 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; 
    } 

回答

81

什么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); 
    } 
} 
+0

我旋转位图仅用于显示的目的。我从来没有将它保存到文件 – Kevin

+3

你不需要保存它;那个'RotateFlip'就可以做到。您可以删除'使用'并添加一个'返回新位图(img);' –

+0

您可能希望从这里获取一些代码,以确保jpeg以比默认的50 http: /stackoverflow.com/questions/1484759/quality-of-a-saved-jpg-in-c-sharp –

8

的错误是在你第一次调用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方法可能会更好。

1

我碰到过,并做了一些修改,我把它运行起来了。我发现了一些其他的例子,并注意到一些对我造成影响的东西。我不得不打电话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); 
    } 
}