2010-02-08 194 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); 
    } 
}