Search code examples
javaimageimage-rotation

How to rotate an image based on two points


I have some images I manipulate, and in these images I always have two points (x1, y1) and (x2, y2). like this:

|----------------|
|                |
|    .           |
|                |
|          .     |
|                |
|----------------|

I need to code an algorythm to align the image like this

|----------------|
|                |
|                |
|    .     .     |
|                |
|                |
|----------------|

I already read this question but the angle obtained by

double angle = Math.Atan2(pointB.Y - pointA.Y, pointB.X - pointA.X);

Is not working when I use this rotation code in java:

public static BufferedImage tilt(BufferedImage image, double angle) {
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = image.getWidth(), h = image.getHeight();
    int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math
            .floor(h * cos + w * sin);
    GraphicsConfiguration gc = getDefaultConfiguration();
    BufferedImage result = gc.createCompatibleImage(neww, newh,
            Transparency.OPAQUE);
    Graphics2D g = result.createGraphics();

    g.setColor(Color.white);
    g.setBackground(Color.white);
    g.fillRect(0, 0, neww, newh);

    g.translate((neww - w) / 2, (newh - h) / 2);

    g.rotate(angle, w / 2, h / 2);
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
}

In the post mentioned before they use the c# code like

myImage.TranslateTransform(-pointA.X, -pointA.Y);
myImage.RotateTransform((float) angle, MatrixOrder.Append);
myImage.TranslateTransform(pointA.X, pointA.Y, MatrixOrder.Append);

Is there anybody that could help with a java implementation for this case?


Solution

  • Ok... to solve the problem I just converted the radians value returned by Math.atan2 to degrees and the rotation worked well.

    Thanx everybody