使用图形2D翻转图像

2022-09-01 16:21:22

我一直在想办法翻转图像一段时间,但还没有弄清楚。

我用来画一个Graphics2DImage

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

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

如果你愿意,你可以看看github上的完整源代码


答案 1

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

答案 2

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

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

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

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

推荐