Question
How can I flip an image vertically or horizontally using Graphics2D in Java?
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ImageFlipper extends JPanel {
private BufferedImage image;
public ImageFlipper(BufferedImage img) {
this.image = img;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Flip image horizontally
g2d.scale(-1, 1);
g2d.drawImage(image, -image.getWidth(), 0, null);
// Alternative: Flip image vertically
// g2d.scale(1, -1);
// g2d.drawImage(image, 0, -image.getHeight(), null);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
BufferedImage img = ...; // Load your image here
ImageFlipper flipper = new ImageFlipper(img);
frame.add(flipper);
frame.setSize(img.getWidth(), img.getHeight());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Answer
Flipping an image in Java using the Graphics2D class involves applying a scaling transformation to the graphics context. This transformation effectively mirrors the image about a specified axis—horizontal or vertical. Below, we provide a guided approach to accomplish this using a custom JPanel.
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ImageFlipper extends JPanel {
private BufferedImage image;
public ImageFlipper(BufferedImage img) {
this.image = img;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Flip image horizontally
g2d.scale(-1, 1);
g2d.drawImage(image, -image.getWidth(), 0, null);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
BufferedImage img = ...; // Load your image here
ImageFlipper flipper = new ImageFlipper(img);
frame.add(flipper);
frame.setSize(img.getWidth(), img.getHeight());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Causes
- The original image needs to be displayed in a flipped orientation.
- Transformations such as scaling can help achieve the desired visual effect.
Solutions
- Use the `scale` method of the Graphics2D class to flip the image.
- Set the origin point to adjust the position of the drawn image after scaling.
Common Mistakes
Mistake: Forgetting to reset the transformation before drawing another component.
Solution: Always call `g2d.setTransform(new AffineTransform());` before drawing any other components.
Mistake: Not properly loading the image, resulting in a null reference.
Solution: Ensure that the image is loaded correctly before creating the ImageFlipper instance.
Helpers
- Java image flipping
- Graphics2D flip image
- Java image manipulation
- How to use Graphics2D
- Java drawing images