Reputation: 781
I'm using the following code to flip an image horizontally. It works, but the image is flipped horizontally and also vertically at the same time. Right facing image, now faces left, but is also vertically flipped. How can I stop the vertical flip? Code:
public static BufferedImage createRotated( BufferedImage image)
{
AffineTransform at = AffineTransform.getRotateInstance(
Math.PI, image.getWidth()/2, image.getHeight()/2 );
return createTransformed(image, at);
}
public static BufferedImage createTransformed( BufferedImage image, AffineTransform at)
{
BufferedImage newImage = new BufferedImage(
image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D gg = newImage.createGraphics();
gg.transform(at);
gg.drawImage(image, 0, 0, null);
gg.dispose();
return newImage;
}
Upvotes: 1
Views: 2628
Reputation: 9303
I've made some performance test and this is a bit more efficient than using AffineTransform
:
public static BufferedImage flipHoriz(BufferedImage image) {
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D gg = newImage.createGraphics();
gg.drawImage(image, image.getHeight(), 0, -image.getWidth(), image.getHeight(), null);
gg.dispose();
return newImage;
}
Upvotes: 1
Reputation: 933
Because you are rotating the image of 180 degrees, not flipping it.
Use the AffineTransform.getScaleInstance(-1, 1);
instead.
EDIT: From here: https://stackoverflow.com/a/9559043/1542532
// Flip the image horizontally
tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-image.getWidth(null), 0);
You must also translate the image because the scale will move the image to the left.
Upvotes: 2