2012-03-04 70 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));