1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- import os
- from PIL import Image
- folder_path = "/Users/zhenqin/Downloads/钢绳" # Replace with the actual folder path
- # 1.将图片统一为纵向 --------------------------------------------------------------------------------------------------
- # Iterate over the files in the folder
- for filename in os.listdir(folder_path):
- if filename.endswith(".jpg") or filename.endswith(".png"): # Adjust file extensions as needed
- file_path = os.path.join(folder_path, filename)
- # Open the image
- image = Image.open(file_path)
- width, height = image.size
- # Compare horizontal and vertical pixel values
- if width > height:
- # Rotate the image 90 degrees clockwise
- rotated_image = image.rotate(-90, expand=True)
- # Save the rotated image, overwrite the original file
- rotated_image.save(file_path)
- print(f"Image '{filename}' rotated.")
- else:
- print(f"No operation required for image '{filename}'.")
- # 2.统一图片分辨率 --------------------------------------------------------------------------------------------------
- def resize_images(folder_path, target_resolution):
- # 遍历文件夹中的所有文件
- for filename in os.listdir(folder_path):
- file_path = os.path.join(folder_path, filename)
- # 检查文件是否是图片
- if not os.path.isfile(file_path) or not any(
- file_path.endswith(extension) for extension in ['.jpg', '.jpeg', '.png']):
- continue
- # 打开图片
- image = Image.open(file_path)
- # 获取原始分辨率
- original_resolution = image.size
- # 计算调整比例
- ratio = min(target_resolution[0] / original_resolution[0], target_resolution[1] / original_resolution[1])
- # 计算调整后的尺寸
- resized_size = (int(original_resolution[0] * ratio), int(original_resolution[1] * ratio))
- # 调整图片分辨率
- resized_image = image.resize(resized_size)
- # 创建空白画布
- canvas = Image.new('RGB', target_resolution, (255, 255, 255))
- # 在画布上居中粘贴调整后的图片
- offset = ((target_resolution[0] - resized_size[0]) // 2, (target_resolution[1] - resized_size[1]) // 2)
- canvas.paste(resized_image, offset)
- # 保存调整后的图片
- canvas.save(file_path)
- # 指定文件夹路径和目标分辨率
- target_resolution = (460, 460) # 替换为你的目标分辨率
- # 调用函数进行图片分辨率统一
- resize_images(folder_path, target_resolution)
|