Flipping square box inside picture help

• 10-16-2010, 03:23 AM
sman865
Flipping square box inside picture help
Hi all, I have an assignment to create a method of the picture class that flips a square box within the picture around a horizontal or vertical line through the middle of the box. (here's an example: pic)

I have worked for a total of 5 hours to only come up with code that does not work, and was wondering if anybody could tell me what I am doing wrong.

The catch here is that I have to do it using the getPixel(x,y) method, nothing simpler will do.

The test file for this program prompts an x, a y, and a size, and the picture repaints itself afterward. Here's the code:

public void flipHorizontal(int x, int y, int size)
{
Pixel a,b,c;
int half = size / 2;
x = x - half;
y = y - half;
int y2 = y;
int x2 = x;
int end = size;
int xend = x + half;
int yend = y + half;
int r,g,bl,r2,g2,b2;

for (y=y2; y < yend; y++)
{

for(x = x2; x < xend+half; x++)
{
a = this.getPixel(x,y);
b = this.getPixel(x,y+end);

r = a.getRed();
g = a.getGreen();
bl = a.getBlue();

r2 = b.getRed();
g2 = b.getGreen();
b2 = b.getBlue();

a.setRed(r2);
a.setGreen(g2);
a.setBlue(b2);

b.setRed(r);
b.setGreen(g);
b.setBlue(bl);

end--;
end--;
}
}
}

any help would be greatly appreciated!

Thanks.
• 10-16-2010, 04:48 AM
pbrockway2
Inside the inner for loop you have

Code:

```a = this.getPixel(x,y); b = this.getPixel(x,y+end);```

If you interchange the colours of a and b won't you induce a *vertical* reflection rather than a horizontal one (as per the method name)? I would have expected the x-coord to be changed.

Secondly you decrement end as you go around the inner loop. But you don't actually reset its value at the start of the outer loop which doesn't look right. Ie you decrement end as you work along a horizontal scan but because you don't reset it, it will have a crazy value for the second and subsequent horizontal scans.

Finally I'm guessing that a Pixel instance is a reference to the pixels in the image so that setting their colour values will result in setting the colours of the original image. But that's only a guess because Pixel is not a standard Java class. (Why not just work with a BufferedImage since these things have get/setRGB() methods that do what you want?). Perhaps a small but runnable example would clarify things - along with a description of the actual behaviour you observe.
• 10-16-2010, 06:39 AM
sman865
I got it! FINALLY

what helped me was you telling me to reset the value of end, thank you sooo much for that.

The reason I am not using a BufferedImage is because my professor specifically said to use the getPixel method, which is inefficient, as you can tell.

Thanks again.
• 10-16-2010, 08:10 PM
pbrockway2
You're welcome. Glad you've figured it out.