Flipping an image means mirroring it on a certain axis. Flipping vertically could be compared to the reflection of yourself in a lake, flipping horizontally is kind of like looking into a mirror. To do a flip, we use drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer); of Graphics2D object. This method lets us draw part of an image into an image, or scale an image etc. The method takes an image, and a set of coordinates of the destination rectangle, it also takes a set of coordinates for the source rectangle of the image you supply. These source coordinates can be manipulated for varying results, as I will show in this next code segment.
For flipping an image horizontally, we give the source rectangle coordinates starting from the top right, and ending at the bottom left like this.
drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer);
g.drawImage(The Source Image, 0, 0, image width, image height, image width, 0, 0, image height, null);
as opposed to the unflipped way
g.drawImage(The Source Image, 0, 0, image width, image height, 0, 0, image width, image height, null);
public static BufferedImage horizontalflip(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(w, h, img.getType());
Graphics2D g = dimg.createGraphics();
g.drawImage(img, 0, 0, w, h, w, 0, 0, h, null);
g.dispose();
return dimg;
}
Running Codes