iii
iii

Reputation: 626

How can I get my image to flip?

I'm having a problem getting an image to flip. My program is supposed to show the default image and the flipped image. I thought that if I could replace the (0,0) pixel of the flipped picture with the (width-1,height-1) of the original picture, it would work, but instead of getting the original image, I get this.

Here is my code:

import java.awt.Color;

public class Horizontal {

public static void main(String[] args)
{
    Picture source = new Picture(args[0]);//name of picture.
    Picture flip = new Picture(source.width(), source.height());//sets the width and height of source

    for (int i =0; i < source.width(); i++)
    {
        int w = 1;
        int sw = source.width()-w;
        for (int j = 0; j < source.width(); j++)
        {
            int h=1;
            int sh =  source.height()-h;
            Color SourceColor =  source.get(sw,sh);// return the the color pixel of (sw,sh)
            flip.set(i, j, SourceColor);//suppose to replace the (i,j) pixel of flip with source's (sw,sh) pixel
            h++;
        }
        w++;
    }
    source.show();// shows the original image
    flip.show(); // shows flipped version of image
}

}

Upvotes: 0

Views: 3292

Answers (1)

Marcin Szymczak
Marcin Szymczak

Reputation: 11433

Chceck this site. It has great info about basic image algorithms in java. You can copy code for flipping an image.

http://www.javalobby.org/articles/ultimate-image/#9

Flipping horizontally:

public static BufferedImage horizontalflip(BufferedImage img) {  

    int w = img.getWidth();  
    int h = img.getHeight();  
    BufferedImage dimg = new BufferedImage(w, h, img.getType());  
    Graphics2D g = dimg.createGraphics();  
    g.drawImage(img, 0, 0, w, h, w, 0, 0, h, null);  
    g.dispose();  
    return dimg;  
}  

Flipping vertically:

public static BufferedImage verticalflip(BufferedImage img) {  
        int w = img.getWidth();  
        int h = img.getHeight();  
        BufferedImage dimg = dimg = new BufferedImage(w, h, img.getColorModel().getTransparency());  
        Graphics2D g = dimg.createGraphics();  
        g.drawImage(img, 0, 0, w, h, 0, h, w, 0, null);  
        g.dispose();  
        return dimg;  
    }  

Upvotes: 1

Related Questions