Reputation: 1422
I have an image with height=576 and width=768 and I stored its pixel information in matrix I[height][width]. Now i want to rotate the image about its center. When we load the image, the upper left corner is actually (0,0).So, i set the origin to center(384,288) and applied the formula: x'=xcos(theta) +ysin(theta) and y'= -xsin(theta) +ycos(theta) (http://en.wikipedia.org/wiki/Transformation_matrix.
Following is my code:
/* ROTATION REQUIRED */
for(i2=0;i2<height2;i2++)
{
for(j2=0;j2<width2;j2++)
{
x_origin=j2 + (width2/2);
y_origin=i2 + (height2/2);
x_transformed=(int)(x_origin*Math.cos(radians) + y_origin*Math.sin(radians));
y_transformed= (int)(-x_origin*Math.sin(radians) + y_origin*Math.cos(radians));
x_new = x_transformed- (width2/2);
y_new = y_transformed- (height2/2);
pix=hw1.Image2[i2][j2]; /*pixel info of original image */
hw1.img2.setRGB(x_new, y_new, pix);
When I do this calculation, my y_transformed comes out to be negative(hence y_new) and therefore, setRGB() functions throws Coordinate Out Of Bound Exception.
Can anyone guide me where am i doing wrong??
Thanks
Upvotes: 0
Views: 281
Reputation: 12224
When you rotate the image, you rotate the corners into negative y (and also X) coordinates. Think about rotating a square 45 degrees about its center. The top and left corners will stick out of the box they were contained by.
This is not a problem mathematically, but it is a problem for the Java graphics framework.
Do your rotation mathematically, and find the minimum x and y, then translate the rotated shape enough so that X and Y are no longer negative before you set the coordinates in the java graphics framework.
Alternatively, just don't plot any points that are less than 0 (X or Y), which will crop parts from your rotated image.
Upvotes: 2