简体   繁体   中英

How to mirror an image horizontally using Java 2D Arrays?

Greetings guys and girls I've stumbled into a problem I can't seem to figure out, and the similar posts have a different structure than what I'm using. Therefore I'd really appreciate some guidance. Let's take a look at my horizontal mirror method:

  public void  mirrorHorizontal(){
  Pixel[][] pixels = this.getPixels2D();     
  Pixel topPixel = null;     
  Pixel bottomPixel = null;     
  int width = pixels[0].length;     
  for (int row = 0; row < pixels.length / 2; row++){       
      for (int col = 0; col < width; col++){         
          bottomPixel = pixels[row][col];        
          topPixel = pixels[row][col];         
          bottomPixel.setColor(topPixel.getColor());       
      }     
  } }

Lets establish that this code was provided to use and modify so I will do my best to explain.

In this for loop what I did was cut the rows in half by diving the pixels.length by 2 so I can achieve the top picture at the top, and one on the bottom.

for (int row = 0; row < pixels.length / 2; row++){  

So I believe here is my problem:

bottomPixel = pixels[row][col];        
topPixel = pixels[row][col];

I do not know what to put inside the bottomPixel [row][col]

I believe it has to render something like this:

  1. 1 2 3 4
  2. 5 6 7 8
  3. 5 6 7 8
  4. 1 2 3 4

However I'm not sure how to modify it to achieve that.

This uses two modified for loops & different values to achieve similar effects to flipping a multi-dimensional array java by AngryDuck.

So in your exsample the bottomPixel and topPixel are exactly the same.

If I understood your question correctly, this will solve your problem:

for (int row = 0; row < pixels.length / 2; row++){       
  for (int col = 0; col < pixels[0].length; col++){                 
      topPixel = pixels[row][col];  
      bottomPixel = pixels[(pixels.length - 1) - i][col];       
      bottomPixel.setColor(topPixel.getColor());       
  }     
} 

I changed the row coordinate of bottomPixel so it will take the mirrored coordinate from the bottom. But this only works if your image has exactly pixels.length / 2 rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM