I'm trying to flip an image in java, but I ran into a problem that I just cannot figure out.
Using a double-for-loop, I'm running through all pixelvalues in the org image, and copying them to the new image in the pixel(width-x-1,y).
The following picture depicts, what happens when I run the method.
The new image, only seems to run through 1/10 of the image' height for some reason. Why is this and how do I fix it?
private Image img;
private Pixel pixel;
private Image newimg;
private Pixel newpixel;
public advancedFilters(Image img)
{
this.img = img;
}
public Image Mirror(){
newimg = new Image(img.getWidth(), img.getHeight(), "newimage");
int curtone;
for (int j=0; j<img.getHeight(); j++) {
for (int i=0; i<img.getWidth(); i++) {
pixel = img.getPixel(i,j);
curtone = pixel.getValue();
newpixel = newimg.getPixel(newimg.getWidth()-i-1, j);
newpixel.setValue(curtone);
}
}
return newimg;
}
Why are you storing the temporary values private Pixel pixel
and private Pixel newpixel
outside of the scope where they're being used? This is unnecessary (from the code that you posted at least) and is asking for trouble. Try this implementation of your algorithm (which appears correct) instead:
private Image img;
private Pixel pixel;
private Image newimg;
private Pixel newpixel;
public advancedFilters(Image img)
{
this.img = img;
}
public Image Mirror(){
newimg = new Image(img.getWidth(), img.getHeight(), "newimage");
for (int j=0; j<img.getHeight(); j++) {
for (int i=0; i<img.getWidth(); i++) {
Pixel oldPixel = img.getPixel(i,j);
int oldPixelVal = oldPixel.getValue();
Pixel mirrorPixel = newimg.getPixel((newimg.getWidth()-i-1), j);
mirrorPixel.setValue(curtone);
}
}
return newimg;
}