Sometimes it is necessary to rework height and width. One of my customer had for instance bad height and width information in images metadata (they were inverted compared to real data).

In the following method, height and width are exchanged:

  static BufferedImage flip(BufferedImage img) {
        int height = img.getHeight();
        int width = img.getWidth();
        BufferedImage resizedImg = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = resizedImg.createGraphics();

        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(img, 0, 0, height, width, null);
        g2.dispose();

        return resizedImg;
    }

Notice: this code does not perform a rotation, but only a resizing. There are some rotations possibilities, on the Graphics2D class which contains a rotate() Javadoc here method

And the calling code is as follows

   public static void main(String[] args) throws IOException {
        String basePath = "./";
        BufferedImage img = ImageIO.read(new File(basePath + "src/main/resources/test.png"));

        BufferedImage flipped = flip(img);

        ImageIO.write(flipped, "png", new File(basePath+"src/main/resources/flipped.png"));

    }

when called on the original image :

it produces this result image :

Complete code :

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

public class ImageFlip {

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

        BufferedImage img = ImageIO.read(new File("src/main/resources/banana.jpg"));

        BufferedImage flipped = flip(img);

        ImageIO.write(flipped, "png", new File("src/main/resources/flipped.jpg"));

    }

    static BufferedImage flip(BufferedImage img) {
        int height = img.getHeight();
        int width = img.getWidth();
        BufferedImage resizedImg = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(img, 0, 0, height, width, null);
        g2.dispose();

        return resizedImg;
    }
}

Previous Post Next Post