Mirroring an image Vertical in Java
Mirroring an image is very easy and quite interesting effect that rarely can be used. Mirroring an image is similar to placing a image on mirror so that left side of image shows up in mirror. We will apply couple different techniques.
Mirroring image pixels along a vertical Line
First of all find the mirroring point. That can be center of each row. Now, what we are going to do is to copy and replace left half of image to right half side. To achieve this we will obtain the width of an image. Now we are change the color of pixel of right pixel(width-x,0) with pixel(0,0) that is most left side. The value of x will change after each iteration until reach middle of image. This will setup new color half image portion of right side with pixel(0,0), pixel(1,0), pixel(2,0) and son on.
We can mirror pixel from left to right and right to left too. Let’s have a look at method below. Add this method to MyPicture class to use it in your code.
The following code mirror image from right to left.
// Vertical mirroring of image from right to left public void mirrorVerticalRL() { //get width of image int width = this.getWidth(); //mirror point of image int mirrorPoint = width / 2; Pixel leftPixel = null; Pixel rightPixel = null; // loop through all the row of image for (int y = 0; y < getHeight(); y++) { // loop from 0 to the middle (mirror point) that is half part of image for (int x = 0; x < mirrorPoint; x++) { //get left pixel of image leftPixel = getPixel(x, y); //get right pixel of image rightPixel = getPixel(width - 1 - x, y); //replace right pixel with left pixel color rightPixel.setColor(leftPixel.getColor()); } } }
Here is the result taken after implementing above method.
Here is another example to mirror image pixel from left to right.
// Vertical mirroring of image from left to right public void mirrorVerticalLR() { //get width of image int width = this.getWidth(); //mirror point of image int mirrorPoint = width / 2; Pixel leftPixel = null; Pixel rightPixel = null; // loop through all the row of image for (int y = 0; y < getHeight(); y++) { // loop from 0 to the middle (mirror point) that is half part of image for (int x = 0; x < mirrorPoint; x++) { //get left pixel of image leftPixel = getPixel(x, y); //get right pixel of image rightPixel = getPixel(width - 1 - x, y); //replace right pixel with left pixel color leftPixel.setColor(rightPixel.getColor()); } } }
No Responses