Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cropping rotated image with same aspect ratio

How can I find out the width and height of the final image when the input image is rotated by given amount of degrees and then cropped to avoid any non-image areas while maintaining the original image aspect ratio.

example: example

like image 793
miki725 Avatar asked Feb 14 '23 23:02

miki725


1 Answers

enter image description here

  • Red rectangle is original image with original aspect ratio.
  • W/t rectangle (enclosed by green and yellow triangles) is rotated image aspect ratio with extend=True.

Here is how to get the w and h.

image = Image.open(...)
rotated = image.rotate(degrees, Image.BICUBIC, True)

aspect_ratio = float(image.size[0]) / image.size[1]
rotated_aspect_ratio = float(rotated.size[0]) / rotated.size[1]
angle = math.fabs(degrees) * math.pi / 180

if aspect_ratio < 1:
    total_height = float(image.size[0]) / rotated_aspect_ratio
else:
    total_height = float(image.size[1])

h = total_height / (aspect_ratio * math.sin(angle) + math.cos(angle))
w = h * aspect_ratio

Now the rotated image can be cropped in the center with wxh dimensions to get the final image.

like image 199
miki725 Avatar answered Feb 27 '23 11:02

miki725