4

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?

Community
  • 1
  • 1
  • When you say not working, what exactly is going on. I use the exact same code (forgot where it came from) which much success. – user489041 Apr 07 '11 at 14:39
  • I mean, the rotation does not align the image correctly. One of my images needs a rotation of 19 degrees but the Math.Atan2(pointB.Y - pointA.Y, pointB.X - pointA.X); returns somehting like 2 – Ademir Constantino Apr 07 '11 at 14:52

3 Answers3

1

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

Thanx everybody

0

for me the below worked to align OMR sheet markings where pointA is TopLeft Corner mark, pointB is BottomLeft corner mark

double angle = Math.Atan2(pointB.x - pointA.x, pointB.y - pointA.y);

Venkat
  • 1
0

If the left point in your example is A, and the right point in your example is B, imagine drawing a point C (A.X, B.Y) that has a 90 degree angle to complete the triangle. IF you use geometry calculation to calculate the angle of corner A, you know by how much to rotate.

NKCSS
  • 2,716
  • 1
  • 22
  • 38