使用Graphics2D翻转图像

我一直试图弄清楚如何翻转图像一段时间,但还没想到。

我正在使用Graphics2D来绘制Image

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

我只需要一种在水平轴或垂直轴上翻转图像的方法。

如果你想要,你可以看看github上的完整源代码 。

来自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); 

翻转图像的最简单方法是对其进行负缩放。 例:

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

那会水平翻转它。 这将垂直翻转:

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

您可以在Graphics上使用变换,这应该可以很好地旋转图像。 下面是一个示例代码,您可以使用它来实现此目的:

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

将图像垂直旋转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));