Java – how to rotate an image based on two points

I have some images I manipulate. In these images, I always have two points (x1, Y1) and (X2, Y2) like this:

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

I need to write an algorythm code to align the images

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

I have read this question, but get the angle

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

When I use this rotation code in Java, it doesn't work:

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,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 posts mentioned earlier, they used c# code and so on

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

Can anyone help with the Java implementation of this case?

Solution

Ok... To solve this problem, I just put math The radian value returned by atan2 is converted to degrees, and the rotation effect is very good

hello everyone

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>