I'm trying to mirror or flip an image but my code only mirrors half the image and I don't know how to fix it. This is the original image: original image I'm trying to get this as my final result: flipped/mirrored image
I also want to clarify that I know I can take advantage of 2DGraphics and the API support but I'm trying to figure out how I can mirror the image by manipulating the 2D array
This is my code and the result that I get:
public static void applyMirror(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
for(int j = 0; j < height; j++){
for(int i = 0, w = width - 1; i < width; i++, w--){
int p = img.getRGB(i, j);
img.setRGB(w, j, p);
}
}
You have to walk for i upto width/2. Otherwise you swap every (i, width - i - 1) twice. ;)
And swap the two opposite pixels.
–-----
for (int i = 0, w = width - 1; i < w; ++i, --w) {
int pi = img.getRGB(i, j);
int pw = img.getRGB(w, j);
img.setRGB(i, j, pw);
img.setRGB(w, j, pi);
}
This ensures you do not write an already changed pixel, as your code did.