考虑到Pillow库的能力边界,不能浪费。
1.可以增加左右翻转、水平翻转吗
2.格式转换(批量转格式)
代码实现
# 获取Quicker传递的变量
files = quicker.context.GetVarValue('files') # 选中的图片文件
rotate = quicker.context.GetVarValue('rotate') # 旋转角度
flip_horizontal = quicker.context.GetVarValue('flip_horizontal') # 水平翻转(左右)
flip_vertical = quicker.context.GetVarValue('flip_vertical') # 垂直翻转(上下)
target_format = quicker.context.GetVarValue('target_format') # 目标格式(如"JPG")
from PIL import Image
import os # 用于处理文件路径
def process_image(image_path):
# 1. 打开图片
with Image.open(image_path) as img:
# 2. 旋转处理(角度不为0时)
if rotate != 0:
img = img.rotate(rotate, expand=True)
# 3. 水平翻转(左右)
if flip_horizontal:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
# 4. 垂直翻转(上下)
if flip_vertical:
img = img.transpose(Image.FLIP_TOP_BOTTOM)
# 5. 格式转换(如果选择了目标格式)
if target_format != "不转换":
# 生成新文件名(原文件名+_converted.新格式)
dirname, filename = os.path.split(image_path)
name, ext = os.path.splitext(filename)
new_filename = f"{name}_converted.{target_format.lower()}" # 小写格式名(如jpg)
new_path = os.path.join(dirname, new_filename)
# 特殊处理:PNG转JPG时,透明背景转为白色
if ext.lower() == ".png" and target_format.upper() == "JPG":
# 创建白色背景图层,合并图片
white_bg = Image.new("RGB", img.size, (255, 255, 255))
if img.mode in ("RGBA", "LA"):
white_bg.paste(img, mask=img.split()[-1]) # 用透明通道作为蒙版
img = white_bg
# 保存转换后的图片(指定格式)
img.save(new_path, format=target_format.upper())
else:
# 不转换格式时,覆盖原文件(旋转/翻转后)
img.save(image_path)
# 批量处理所有选中的图片
for img_path in files:
process_image(img_path)