Flip Image with Graphics2D

Fuze picture Fuze · Mar 4, 2012 · Viewed 49k times · Source

I've been trying to figure out how to flip an image for a while, but haven't figured out yet.

I'm using Graphics2D to draw an Image with

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

I just need a way to flip the image on the horizontal or vertical axis.

If you want you can have a look at the full source on github.

Answer

I82Much picture I82Much · Mar 4, 2012

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