Flip (Mirror) Image Java

96 Views Asked by At

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);
  }
}

my result

2

There are 2 best solutions below

2
Joop Eggen On BEST ANSWER

You have to walk for i upto width/2. Otherwise you swap every (i, width - i - 1) twice. ;)

And swap the two opposite pixels.

–-----

Code

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.

1
MadProgrammer On

Simply make use of the available API support. A really simple trick is to simply scale the image using a negative value in the axis you want mirrored, for example...

BufferedImage mirrored = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = mirrored.createGraphics();
g2d.scale(-1, 1);
g2d.translate(-source.getWidth(), 0);
g2d.drawImage(source, 0, 0, null);
g2d.dispose();

Not only is it faster, it's also a lot simpler

enter image description hereenter image description here