python --Rotate picture (horizontal picture to vertical picture)

horizontal flip

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)

vertical flip

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)

In the above code, flip_horizontaland flip_verticalare the functions of horizontal flip and vertical flip respectively. image_pathis the path of the input image and output_paththe path of the output image.

In the usage example, first call to flip_horizontalflip the image horizontally, and then call to flip_verticalflip the image vertically. One or both of these methods can be selected according to actual needs.

Horizontal to 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)

Vertical to horizontal

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)

The function and judgment logic in the above code are similar to the example of converting a horizontal image to a vertical image, except that the judgment condition is changed to the width of the image being smaller than the height. If it is a vertical image, perform a rotation operation to convert it into a horizontal image; if it is a horizontal image, it will be directly saved to the output path. The angle of rotation can also be modified to Image.ROTATE_270(rotate 90 degrees counterclockwise) or other desired angles.

Guess you like

Origin blog.csdn.net/weixin_44634704/article/details/129747073