python --旋转图片(横图转竖图)
from PIL import Image
def flip_horizontal(image_path, output_path):
with Image.open(image_path) as image:
flipped_image = image.transpose(method=Image.FLIP_LEFT_RIGHT)
flipped_image.save(output_path)
from PIL import Image
def flip_vertical(image_path, output_path):
with Image.open(image_path) as image:
flipped_image = image.transpose(method=Image.FLIP_TOP_BOTTOM)
flipped_image.save(output_path)
上述代码中,flip_horizontal 和 flip_vertical 分别是水平翻转和垂直翻转的函数。image_path 是输入图片的路径,output_path 是输出图片的路径。
使用示例中先调用 flip_horizontal 水平翻转图片,再调用 flip_vertical 垂直翻转图片。可以根据实际需求选择其中一种或两种方式。
from PIL import Image
def rotate_image(image_path, output_path):
with Image.open(image_path) as image:
if image.width > image.height:
# 横图,需要旋转
rotated_image = image.transpose(method=Image.ROTATE_270)
rotated_image.save(output_path)
else:
# 竖图,不需要操作
image.save(output_path)
# 示例用法
image_path = "path/to/image"
output_path = "path/to/output"
rotate_image(image_path, output_path)
from PIL import Image
def rotate_image(image_path, output_path):
with Image.open(image_path) as image:
if image.width < image.height:
# 竖图,需要旋转
rotated_image = image.transpose(method=Image.ROTATE_90)
rotated_image.save(output_path)
else:
# 横图,不需要操作
image.save(output_path)
# 示例用法
image_path = "path/to/image"
output_path = "path/to/output"
rotate_image(image_path, output_path)
上述代码中的函数和判断逻辑与将横图转成竖图的示例类似,只是将判断条件改为图片的宽度小于高度。如果是竖图,则进行旋转操作,将其转成横图;如果是横图,则直接保存到输出路径。旋转的角度也可以修改成 Image.ROTATE_270(逆时针旋转 90 度)或其他需要的角度。