0

This is some code that I have written to rotate an image 90 degrees clockwise. This works fine when the image's height matches its width. But when this is not the case, the image has a black edge at the end where the rest of the image is supposed to be. Any help is appreciated

public void rotate(){
    int y = this.image.length;
    int x = this.image[0].length;
    int[][] rotate = new int[x][y];
    UI.println(y);
    UI.println(x);
    for(int row = 0; row<x/2; row++){
        for(int col = 0; col < ((y+1)/2); col++){
            int temp = this.image[row][col];
            rotate[row][col] = this.image[y-1-col][row];
            rotate[y-1-col][row] = this.image[y-1-row][y-1-col];
            rotate[y-1-row][y-1-col] = this.image[col][y-1-row];
            rotate[col][y-1-row] = temp;
        }
    }
    int[][] image = new int[x][y]; 
    this.image = rotate;
neve_exe
  • 19
  • 2
  • Possible dublicate: http://stackoverflow.com/questions/8639567/java-rotating-images – nikli May 23 '16 at 05:18
  • 1
    The question marked as duplicate is wrong. Here op wanted to program to rotate image. not to use any utility method provided by awt. – afzalex May 23 '16 at 05:25
  • Im not sure you understand it - can you spin your head around it? – gpasch May 23 '16 at 16:48

1 Answers1

0

Transformation matrix for rotation is

| c   -s  0 |
| s   c   0 |
| 0   0   1 |

c = cos theta and s = sin theta
Transofromation matrix for translation is

| 1   0   xr |
| 0   1   yr |
| 0   0   1  |

You need translate translate center of object to origin
then rotate
then translate back

|1  0  xr|   |c  -s  0|   |1  0  -xr|   |x|
|0  1  yr| x |s  c   0| x |0  1  -yr| x |y|
|0  0  1 |   |0  0   1|   |0  0    1|   |1|

After solving it you will get

|x*c-y*s-xr*c+yr*s+xr|
|x*s+y*c-xr*s-yr*c+yr|
|          1         |

So new point (x2, y2) is such that

x2 = x*c-y*s-xr*c+yr*s+xr
y2 = x*s+y*c-xr*s-yr*c+yr

put c = 0 (because cos90 = 0)
and s = 1 (because sin90 = 1)

x2 = -y+yr+xr
y2 = x-xr+yr
afzalex
  • 8,598
  • 2
  • 34
  • 61