python – 以相同的宽高比裁剪旋转的图像

当输入图像旋转给定的度数然后裁剪以避免任何非图像区域同时保持原始图像宽高比时,如何找出最终图像的宽度和高度.

例:

最佳答案 >红色矩形是具有原始宽高比的原始图像.

>旋转W / t矩形(由绿色和黄色三角形包围)

图像宽高比与extend = True.

以下是如何获得w和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

现在旋转的图像可以在中心被裁剪,尺寸为wxh
得到最终的图像.

点赞