[Python] 纯文本查看 复制代码
import PySimpleGUI as sg
import os
from PIL import Image
def create_3x3_image(input_image_path, output_image_path, new_width, new_height):
img = Image.open(input_image_path)
width, height = img.size
# 计算新图片的宽度和高度
new_width = width * new_width
new_height = height * new_height
new_img = Image.new('RGB', (new_width, new_height))
# 粘贴原始图片到新图片的9个位置
for i in range(new_width // width):
for j in range(new_height // height):
new_img.paste(img, (i * width, j * height))
new_img.save(output_image_path)
def batch_process_images(input_folder, output_folder, new_width, new_height):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.tiff')):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, f'3x3_{filename}')
create_3x3_image(input_path, output_path, new_width, new_height)
print(f'Processed {filename}')
def batch_process_images(input_folder, output_folder, new_width, new_height):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
sg.cprint(f'完成处理')
di = 1
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.tiff')):
# 分离文件名和扩展名
base, ext = os.path.splitext(filename)
# 构建新的文件名,添加“3x3”后缀
new_filename = f"{base}_3x3{ext}"
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, new_filename)
# 调用函数处理图片
create_3x3_image(input_path, output_path, new_width, new_height)
# sg.cprint(f'Processed {filename} to {new_filename}')
sg.cprint(f'第{di}个图片-- {filename} to {new_filename}')
di += 1
# ...(其他代码保持不变)
def main():
layout = [
[sg.Text('待处理文件夹:', size=(15, 1)),sg.InputText(key='-input_folder-'), sg.FolderBrowse('选择文件夹')],
[sg.Text('输出文件夹:', size=(15, 1)), sg.InputText(key='-output_folder-'), sg.FolderBrowse('选择文件夹')],
[sg.Text('列:', size=(2, 1)), sg.InputText(key='-newwidth-', size=(5, 1)), sg.Text('行:', size=(2, 1)),
sg.InputText(key='-newheight-', size=(5, 1)), sg.Button('拼接批处理')],
[sg.ML(size=(80, 15), reroute_cprint=True, )],
# [sg.Button('开始批处理'), sg.OUTPUT(size=(80, 15),key='-OUTPUT-')],
# [sg.Output(size=(80, 2), key='-OUTPUT-')],
]
window = sg.Window('批量实现 一张图片复制拼接', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == '退出':
break
if event == '拼接批处理':
input_folder = values['-input_folder-']
output_folder = values['-output_folder-']
new_width = int(values['-newwidth-'])
new_height = int(values['-newheight-'])
if not input_folder or not output_folder or new_width <= 0 or new_height <= 0:
sg.popup_error('请确保所有输入都正确无误!')
continue
batch_process_images(input_folder, output_folder, new_width, new_height)
sg.cprint(f'---处理完成,输出到 {output_folder}---')
# window['-OUTPUT-'].update(f'处理完成,输出到 {output_folder}')
window.close()
main()