import osimport mathfrom PIL import Imagedef create_image_grid_adaptive(source_folder, output_path, columns_per_row, target_height_setting): valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff') image_files = [ os.path.join(source_folder, f) for f in os.listdir(source_folder) if f.lower().endswith(valid_extensions) ] if not image_files: print(f"错误:在 {source_folder} 中没有找到图片文件!") return print(f"找到 {len(image_files)} 张图片") resized_dims = [] for file_path in image_files: img = Image.open(file_path) w, h = img.size ratio = target_height_setting / h new_w = int(w * ratio) new_h = target_height_setting resized_dims.append((new_w, new_h)) num_rows = math.ceil(len(image_files) / columns_per_row) col_widths = [] for col in range(columns_per_row): max_w = 0 for row in range(num_rows): idx = row * columns_per_row + col if idx < len(resized_dims): w, _ = resized_dims[idx] if w > max_w: max_w = w col_widths.append(max_w) total_width = sum(col_widths) total_height = num_rows * target_height_setting print(f"画布尺寸:{total_width} × {total_height}") grid_image = Image.new('RGB', (total_width, total_height), color='white') for index, file_path in enumerate(image_files): img = Image.open(file_path) if img.mode != 'RGB': img = img.convert('RGB') new_w, new_h = resized_dims[index] img = img.resize((new_w, new_h), Image.LANCZOS) row = index // columns_per_row col = index % columns_per_row x_offset = sum(col_widths[:col]) y_offset = row * target_height_setting grid_image.paste(img, (x_offset, y_offset)) print(f"已粘贴第 {index + 1}/{len(image_files)} 张图片") output_dir = os.path.dirname(output_path) if output_dir and not os.path.exists(output_dir): os.makedirs(output_dir) grid_image.save(output_path, quality=95) print(f"拼接完成!已保存到:{output_path}")if __name__ == "__main__": input_path = r".\input" output_path_filename = r".\output\combined.png" user_input = input("请设置每行的列数 (默认为 3): ") columns_per_row = int(user_input) if user_input.strip() else 3 target_height_setting = 1200 create_image_grid_adaptive( source_folder=input_path, output_path=output_path_filename, columns_per_row=columns_per_row, target_height_setting=target_height_setting )input("图片拼接完成,按回车键退出......")