2012-10-30 43 views
0

我在內存中保存了一個java.Awt Images的列表,並且需要旋轉它們。我已經閱讀了一些解決方案,但它們處理的是改變圖像的顯示方式,而不是真正旋轉圖像本身。 我需要旋轉圖像本身,而不是以旋轉的方式繪製。這怎麼能達到?在內存中旋轉圖像

+0

是否要物理旋轉像素?我在試圖解決你試圖達到的目標時遇到困難?正在加載圖像,旋轉它們在內存中,並保存它們退出或什麼? – MadProgrammer

+2

AffineTransform,Graphics2D和BufferedImage將是一個很好的起點。 – Neet

+0

我從掃描儀獲取圖像,然後將它們顯示在屏幕上,最後將它們保存在磁盤上;我實際上需要旋轉像素。 – Enoon

回答

2

以下代碼將以角度旋轉任意角度的圖像。

degrees的正值將順時針旋轉圖像,逆時針旋轉負值。 生成的圖像將被調整大小,以便旋轉的圖像完全適合它。
我已經用jpgpng圖像文件作爲輸入來測試它。

public static BufferedImage rotateImage(BufferedImage src, double degrees) { 
double radians = Math.toRadians(degrees); 

int srcWidth = src.getWidth(); 
int srcHeight = src.getHeight(); 

/* 
* Calculate new image dimensions 
*/ 
double sin = Math.abs(Math.sin(radians)); 
double cos = Math.abs(Math.cos(radians)); 
int newWidth = (int) Math.floor(srcWidth * cos + srcHeight * sin); 
int newHeight = (int) Math.floor(srcHeight * cos + srcWidth * sin); 

/* 
* Create new image and rotate it 
*/ 
BufferedImage result = new BufferedImage(newWidth, newHeight, 
    src.getType()); 
Graphics2D g = result.createGraphics(); 
g.translate((newWidth - srcWidth)/2, (newHeight - srcHeight)/2); 
g.rotate(radians, srcWidth/2, srcHeight/2); 
g.drawRenderedImage(src, null); 

return result; 
} 
+0

謝謝,但這似乎「吃了」邊界的一些像素。 – Enoon

+0

不客氣。但注意,這隻適用於方形圖像。 (或與180度ratations),但正確調整圖像大小不應該是挑戰。更直接的方式,我只能360度旋轉。 ;-) –

+0

現在,將圖像旋轉到任意大小的圖像上真的是一個很大的挑戰。這是我終於出來的,我用新的代碼更新了我的答案。爲我工作就像一個魅力。特殊功能:您還可以順時針和逆時針旋轉。結果-45和+135度是相同的。 –