2012-03-04 140 views
16

我一直在試圖弄清楚如何翻轉圖像一段時間,但還沒有弄清楚。使用Graphics2D翻轉圖像

我使用的Graphics2D繪製一個圖像的

g2d.drawImage(image, x, y, null) 

我只需要一種方法來翻轉在水平軸或垂直軸的圖像。

如果你願意,你可以看看完整的源代碼在GitHub上(link

編輯:Woops,我的意思是放在標題「炫」,而不是「旋轉」。

+3

而不必我們來看看你的整個源,作出[SSCCE(http://sscce.org) 。 – Jeffrey 2012-03-04 21:33:22

+1

如果你谷歌「Graphics2D旋轉圖像」,你會發現很多教程 – DNA 2012-03-04 21:35:21

回答

48

http://examples.javacodegeeks.com/desktop-java/awt/image/flipping-a-buffered-image

// Flip the image vertically 
AffineTransform tx = AffineTransform.getScaleInstance(1, -1); 
tx.translate(0, -image.getHeight(null)); 
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); 
image = op.filter(image, null); 


// Flip the image horizontally 
tx = AffineTransform.getScaleInstance(-1, 1); 
tx.translate(-image.getWidth(null), 0); 
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); 
image = op.filter(image, null); 

// Flip the image vertically and horizontally; equivalent to rotating the image 180 degrees 
tx = AffineTransform.getScaleInstance(-1, -1); 
tx.translate(-image.getWidth(null), -image.getHeight(null)); 
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); 
image = op.filter(image, null); 
+1

對於'-1' :-)一個相關的例子被提及[這裏](http://stackoverflow.com/a/9373195/230513) 。 – trashgod 2012-03-04 22:36:46

3

你可以在你的Graphics上使用變換,它應該旋轉圖像。下面是一個示例代碼,你可以用它來達致這:

AffineTransform affineTransform = new AffineTransform(); 
//rotate the image by 45 degrees 
affineTransform.rotate(Math.toRadians(45), x, y); 
g2d.drawImage(image, m_affineTransform, null); 
25

最簡單的方式翻轉圖像是由負縮放它。 例如:

g2.drawImage(image, x + width, y, -width, height, null); 

這將水平翻轉它。這將垂直翻轉:

g2.drawImage(image, x, y + height, width, -height, null); 
+11

這幾乎是不錯的。它應該像 g2.drawImage(image,x + height,y,width,-height,null);原因是因爲負尺度會將圖像移動到左側,因此您必須補償此移動。 – 2014-03-23 14:35:26

+1

是的+1 @ T.G爲平衡消極。 – 2015-01-10 21:56:49

+0

我相信這比使用AffineTransform更高效。任何人糾正我,如果我錯了。 (1) – user3437460 2015-10-21 17:22:27

0

旋轉圖像垂直180度

File file = new File(file_Name); 
FileInputStream fis = new FileInputStream(file); 
BufferedImage bufferedImage = ImageIO.read(fis); //reading the image file   
AffineTransform tx = AffineTransform.getScaleInstance(-1, -1); 
tx.translate(-bufferedImage.getWidth(null), -bufferedImage.getHeight(null)); 
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); 
bufferedImage = op.filter(bufferedImage, null); 
ImageIO.write(bufferedImage, "jpg", new File(file_Name));