
Python
1. 设置画布的中心点。它通常是画布的中心或者是需要旋转的图像的中心点。
2. 创建一个变换矩阵,以后可以在矩阵中应用旋转角度。
3. 使用变换矩阵将画布旋转。这可以通过使用Canvas对象的rotate()方法来完成。
以下是一个示例代码,演示如何旋转画布:
Python
from PIL import Image, ImageDraw
# 加载需要旋转的图像
image = Image.open('image.jpg')
# 创建一个 45 度的旋转矩阵
angle = 45
theta = angle * math.pi / 180 # 将角度转化为弧度
cos_val = math.cos(theta)
sin_val = math.sin(theta)
rotation_matrix = (cos_val, -sin_val, sin_val, cos_val, 0, 0)
# 旋转图像
rotated_image = image.rotate(angle, expand=True)
# 创建一个新的画布
canvas = Image.new('RGBA', rotated_image.size, (255, 255, 255, 0))
# 将旋转的图像绘制到画布中
canvas.paste(rotated_image, (0, 0), rotated_image.convert('RGBA'))
# 应用旋转矩阵,将画布旋转到原来的位置
draw = ImageDraw.Draw(canvas)
draw.transform(rotation_matrix)
# 保存旋转后的图像
canvas.save('rotated-image.jpg')
注意,如果不使用expand=True参数对rotate()方法进行调用,那么在旋转过程中可能会出现图像被裁剪的现象。
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号