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
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);
You need to know the width and height of the image to make sure it's properly scaled:
int width = image.getWidth(); int height = image.getHeight();
Then, you need to draw it:
//Flip the image both horizontally and vertically
g2d.drawImage(image, x+(width/2), y+(height/2), -width, -height, null);
//Flip the image horizontally
g2d.drawImage(image, x+(width/2), y-(height/2), -width, height, null);
//Flip the image vertically
g2d.drawImage(image, x-(width/2), y+(height/2), width, -height, null);
This is how I do it, anyways.
You can use a transform on your Graphics
, that should rotate the image just fine. Below is a sample code that you can use to acheive this:
AffineTransform affineTransform = new AffineTransform();
//rotate the image by 45 degrees
affineTransform.rotate(Math.toRadians(45), x, y);
g2d.drawImage(image, m_affineTransform, null);
Rotate Image Vertical 180 Degrees
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));
The easiest way to flip the image is by negative scaling it. Example:
g2.drawImage(image, x + width, y, -width, height, null);
That will flip it horizontally. This will flip it vertically:
g2.drawImage(image, x, y + height, width, -height, null);