0

I wanted to flip original image horizontally and create an image in the same folder, but it does not create a new image. Thanks in advance

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImagesFlipHorizontally {

public static void main(String[] args) throws IOException {

    File location1 = new File("E:\\Users/Peter/Downloads/moon1.jpg");
    BufferedImage image = ImageIO.read(location1);

    File location2 = new File("E:\\Users/Peter/Downloads/moon1mirror.jpg");
    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage mirror = mirrorimage (image, width, height);
    ImageIO.write(mirror, "jpg", location2);

}


    private static BufferedImage mirrorimage (BufferedImage img, int w, int h) {

        BufferedImage horizontallyflipped = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        for (int xx = w-1; xx > 0; xx--) {
            for (int yy = 0; yy < h; yy++) {

                img.setRGB(w-xx, yy, img.getRGB(xx, yy));

            }
        }

        return horizontallyflipped;

    }

}

h20002000
  • 73
  • 7

1 Answers1

0

Besides doing xx >= 0 the swapping was not done.

private static BufferedImage mirrorimage (BufferedImage img, int w, int h) {
    BufferedImage horizontallyflipped = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    for (int yy = 0; yy < h; yy++) {
        for (int xx = 0; xx < w/2; xx++) {
            int c = img.getRGB(xx, yy);
            img.setRGB(xx, yy, img.getRGB(w - 1 - xx, yy));
            img.setRGB(w - 1 - xx, yy, c);
        }
    }
    return horizontallyflipped;
}

There are faster means, like Flip Image with Graphics2D

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138