Home > database >  Rotate an image by 90 180 and 270 degrees when width and height can be any size
Rotate an image by 90 180 and 270 degrees when width and height can be any size

Time:09-03

I am having trouble writing a function that takes a BufferedImage and a Cardinal Direction and rotates the image accordingly. I have looked on many threads on stack and tried implementing myself while going over the docs for some time now and the best I'm getting is that the image seems to be rotating, however the last pixel is correct and the rest are set white or transparent not sure.

Here is where I have got so far:

private BufferedImage rotateImg(BufferedImage image, String direction){

    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage rotated = null;

    for(int y = 0; y < height; y  ){
        for(int x = 0; x < width; x  ){
            switch(direction){
                case "SOUTH":
                    rotated = new BufferedImage(width, height, image.getType());
                    rotated.setRGB((width - 1) - x, (height - 1) - y, image.getRGB(x,y));
                    break;
                case "WEST":
                    //ROTATE LEFT
                    rotated = new BufferedImage(height, width, image.getType());
                    rotated.setRGB(y, (width - 1) - x, image.getRGB(x,y));
                    break;
                case "EAST":
                    //ROTATE RIGHT
                    rotated = new BufferedImage(height, width, image.getType());
                    rotated.setRGB((height - 1) - y,  x, image.getRGB(x,y));
                    break;
                default:
                    return image;
            }
        }
    }
    return rotated;
}

Below there are four images but as they are so small its really hard to see them. A bit of browser zoom will show them.

enter image description here enter image description here enter image description here enter image description here

When you get close the cyan pixel is staying where it should for the rotation. Its just im loosing the rest of the image.

CodePudding user response:

I don't know if there's a fixed requirement to rotate this image by individual pixels or not, but I'm far to simple minded to even be bothered trying.

Instead, I'd (personally) drop straight into the Graphics API itself, for example...

public static BufferedImage rotateBy(BufferedImage source, double degrees) {
    // The size of the original image
    int w = source.getWidth();
    int h = source.getHeight();
    // The angel of the rotation in radians
    double rads = Math.toRadians(degrees);
    // Some nice math which demonstrates I have no idea what I'm talking about
    // Okay, this calculates the amount of space the image will need in
    // order not be clipped when it's rotated
    double sin = Math.abs(Math.sin(rads));
    double cos = Math.abs(Math.cos(rads));
    int newWidth = (int) Math.floor(w * cos   h * sin);
    int newHeight = (int) Math.floor(h * cos   w * sin);

    // A new image, into which the original can be painted
    BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    // The transformation which will be used to actually rotate the image
    // The translation, actually makes sure that the image is positioned onto
    // the viewable area of the image
    AffineTransform at = new AffineTransform();
    at.translate((newWidth - w) / 2, (newHeight - h) / 2);

    // And we rotate about the center of the image...
    int x = w / 2;
    int y = h / 2;
    at.rotate(rads, x, y);
    g2d.setTransform(at);
    // And we paint the original image onto the new image
    g2d.drawImage(source, 0, 0, null);
    g2d.dispose();

    return rotated;
}

This method will create a new image large enough to fit the rotated version of the source image.

You could then drop it into a helper class, add some helper methods and have a basic worker (and re-usable) solution, for example...

public class ImageUtilities {

    public enum Direction {
        NORTH, SOUTH, EAST, WEST
    }

    public static BufferedImage rotateBy(BufferedImage source, Direction direction) {
        switch (direction) {
            case NORTH:
                return source;
            case SOUTH:
                return rotateBy(source, 180);
            case EAST:
                return rotateBy(source, 90);
            case WEST:
                return rotateBy(source, -90);
        }
        return null;
    }

    public static BufferedImage rotateBy(BufferedImage source, double degrees) {
        // The size of the original image
        int w = source.getWidth();
        int h = source.getHeight();
        // The angel of the rotation in radians
        double rads = Math.toRadians(degrees);
        // Some nice math which demonstrates I have no idea what I'm talking about
        // Okay, this calculates the amount of space the image will need in
        // order not be clipped when it's rotated
        double sin = Math.abs(Math.sin(rads));
        double cos = Math.abs(Math.cos(rads));
        int newWidth = (int) Math.floor(w * cos   h * sin);
        int newHeight = (int) Math.floor(h * cos   w * sin);

        // A new image, into which the original can be painted
        BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotated.createGraphics();
        // The transformation which will be used to actually rotate the image
        // The translation, actually makes sure that the image is positioned onto
        // the viewable area of the image
        AffineTransform at = new AffineTransform();
        at.translate((newWidth - w) / 2, (newHeight - h) / 2);

        // And we rotate about the center of the image...
        int x = w / 2;
        int y = h / 2;
        at.rotate(rads, x, y);
        g2d.setTransform(at);
        // And we paint the original image onto the new image
        g2d.drawImage(source, 0, 0, null);
        g2d.dispose();

        return rotated;
    }
}

(although I might use RIGHT, LEFT, UPSIDE or something, but that's me :P)

Runnable example...

enter image description here

import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage masterImage;
        private BufferedImage northImage;
        private BufferedImage southImage;
        private BufferedImage eastImage;
        private BufferedImage westImage;

        public TestPane() throws IOException {
            masterImage = ImageIO.read(new File("/absolute/path/to/your/image.png"));

            northImage = ImageUtilities.rotateBy(masterImage, ImageUtilities.Direction.NORTH);
            southImage = ImageUtilities.rotateBy(masterImage, ImageUtilities.Direction.SOUTH);
            eastImage = ImageUtilities.rotateBy(masterImage, ImageUtilities.Direction.EAST);
            westImage = ImageUtilities.rotateBy(masterImage, ImageUtilities.Direction.WEST);

            setLayout(new GridLayout(3, 3));

            add(new JLabel(""));
            add(new JLabel(new ImageIcon(northImage)));
            add(new JLabel(""));

            add(new JLabel(new ImageIcon(westImage)));
            add(new JLabel(new ImageIcon(masterImage)));
            add(new JLabel(new ImageIcon(eastImage)));

            add(new JLabel(""));
            add(new JLabel(new ImageIcon(southImage)));
            add(new JLabel(""));
        }
    }

    public class ImageUtilities {

        public enum Direction {
            NORTH, SOUTH, EAST, WEST
        }

        public static BufferedImage rotateBy(BufferedImage source, Direction direction) {
            switch (direction) {
                case NORTH:
                    return source;
                case SOUTH:
                    return rotateBy(source, 180);
                case EAST:
                    return rotateBy(source, 90);
                case WEST:
                    return rotateBy(source, -90);
            }
            return null;
        }

        public static BufferedImage rotateBy(BufferedImage source, double degrees) {
            // The size of the original image
            int w = source.getWidth();
            int h = source.getHeight();
            // The angel of the rotation in radians
            double rads = Math.toRadians(degrees);
            // Some nice math which demonstrates I have no idea what I'm talking about
            // Okay, this calculates the amount of space the image will need in
            // order not be clipped when it's rotated
            double sin = Math.abs(Math.sin(rads));
            double cos = Math.abs(Math.cos(rads));
            int newWidth = (int) Math.floor(w * cos   h * sin);
            int newHeight = (int) Math.floor(h * cos   w * sin);

            // A new image, into which the original can be painted
            BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = rotated.createGraphics();
            // The transformation which will be used to actually rotate the image
            // The translation, actually makes sure that the image is positioned onto
            // the viewable area of the image
            AffineTransform at = new AffineTransform();
            at.translate((newWidth - w) / 2, (newHeight - h) / 2);

            // And we rotate about the center of the image...
            int x = w / 2;
            int y = h / 2;
            at.rotate(rads, x, y);
            g2d.setTransform(at);
            // And we paint the original image onto the new image
            g2d.drawImage(source, 0, 0, null);
            g2d.dispose();

            return rotated;
        }
    }
}

But the image is rotating in the wrong direction!

Okay, so change the angle of rotation to meet your needs!

CodePudding user response:

As commented, the actual code is creating a new image for each pixel, that is, inside the inner loop. Only the image created in the last iteration is returned, containing just the last pixel.

The following code creates one single image - I tried to maintain the original code as much as possible:

private static BufferedImage rotateImg(BufferedImage image, String direction){

    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage rotated = null;


    switch(direction){
        case "SOUTH":
            rotated = new BufferedImage(width, height, image.getType());
            for(int y = 0; y < height; y  ){
                for(int x = 0; x < width; x  ){
                    rotated.setRGB((width - 1) - x, (height - 1) - y, image.getRGB(x,y));
                }
            }
            break;
        case "WEST":
            //ROTATE LEFT
            rotated = new BufferedImage(height, width, image.getType());
            for(int y = 0; y < height; y  ){
                for(int x = 0; x < width; x  ){
                    rotated.setRGB(y, (width - 1) - x, image.getRGB(x,y));
                }
            }
            break;
        case "EAST":
            //ROTATE RIGHT
            rotated = new BufferedImage(height, width, image.getType());
            for(int y = 0; y < height; y  ){
                for(int x = 0; x < width; x  ){
                    rotated.setRGB((height - 1) - y,  x, image.getRGB(x,y));
                }
            }
            break;
        default:
            return image;
    }
    return rotated;
}

To avoid having the loop code repeated (easier to maintain) we can use two functions - calX and calcY:

private static BufferedImage rotateImg(BufferedImage image, String direction){

    int width = image.getWidth();
    int height = image.getHeight();
    BufferedImage rotated = null;

    IntBinaryOperator calcX;
    IntBinaryOperator calcY;

    switch(direction){
        case "SOUTH":
            rotated = new BufferedImage(width, height, image.getType());
            calcX = (x, y) -> (width - 1) - x;
            calcY = (x, y) -> (height - 1) - y;
            break;
        case "WEST":
            //ROTATE LEFT
            rotated = new BufferedImage(height, width, image.getType());
            calcX = (x, y) -> y;
            calcY = (x, y) -> (width - 1) - x;
            break;
        case "EAST":
            //ROTATE RIGHT
            rotated = new BufferedImage(height, width, image.getType());
            calcX = (x, y) -> (height - 1) - y;
            calcY = (x, y) -> x;
            break;
        default:
            return image;
    }
    for(int y = 0; y < height; y  ){
        for(int x = 0; x < width; x  ){
            rotated.setRGB(calcX.applyAsInt(x, y), calcY.applyAsInt(x, y), image.getRGB(x,y));
        }
    }
    return rotated;
}
  •  Tags:  
  • java
  • Related