Initially, there was a red image, in order to rotate it without loss, a temporary yellow is created, but it is redundant.

StartStart

It is required to cut a temporary yellow to green.

It is understood that the original image can be of arbitrary size. The angle of rotation is also arbitrary.

  • empty spaces become transparent (alpha channel is used) - stupidcoder
  • ru.stackoverflow.com/a/480803/178988 - but then they found a bug, but I still did not fix it :( - Qwertiy
  • partially solved the problem, but at subsequent turns already a new picture, the result each time increases in size - stupidcoder
  • Well, usually it should be, but if not, then wrote another answer. - Qwertiy

3 answers 3

If you draw a rotated rectangle and its bounding rectangle, and mark angles equal to the rotation angle Fi, you can see, for example, that

CD = DH + HC = EH * Cos(Fi) + GH * Sin(Fi) 

enter image description here

and the formulas for size will be:

 New_Height = Old_Width * Abs(Sin(Fi)) + Old_Height * Abs(Cos(Fi)) New_Width = Old_Width * Abs(Cos(Fi)) + Old_Height * Abs(Sin(Fi)) 

    Since you do not specify any details, the answer will be general:

    1. Calculate the center point of the picture O
    2. Calculate the angle point of the picture C
    3. Rotate the picture around the center at a certain angle known to you. A
    4. Rotate the corner point of the picture to the same angle.

       x = Ox + (Cx - Ox) * Cos(A) + (Cy - Oy) * Sin(A); y = Oy - (Cx - Ox) * Sin(A) + (Cy - Oy) * Cos(A); 
    5. Here you have the x and y coordinates of the rotated point.

    6. By repeating 4 times for all angles, you get the min-max values ​​of the bounding box.

    PS If you have a square and a point of rotation in the center, then the coordinates of 1 angle are enough. 4 corners - this is a general solution, it is convenient for rectangles not exactly lying in the center.

      If you need to remove all transparent edges, then we simply verify for each of them how much transparent we can cut. Get 4 coordinates by which you need to cut a rectangle (inclusive).

       var l, t, r, b; for (l=0; l<width; ++l) for (var q=0; q<height; ++q) if (!isTransparent(l, q)) break; for (r=width-1; r>=l; --r) for (var q=0; q<height; ++q) if (!isTransparent(r, q)) break; for (t=0; t<height; ++t) for (var q=0; q<width; ++q) if (!isTransparent(q, t)) break; for (b=height-1; b>=t; --b) for (var q=0; q<width; ++q) if (!isTransparent(q, b)) break; crop(l, t, r, b); 
      • It is worth noting that when you re-rotate, the rectangle will grow slightly, due to repeated interpolation of pixels at the edges / corners. But this is more likely a problem of the TS algorithm itself - it is better to rotate the image every time from its original position. - Kromster