用Python合成瀑布流图片
Talk is cheap, show the code:
import glob
import random
from PIL import Imagedef create_collage(image_folder, output_path, num_columns=4, column_width=300, margin=10, background_color=(255, 255, 255)):# 1. 获取当前目录下的所有图片image_paths = glob.glob(image_folder + '/*')random.shuffle(image_paths) # 随机排序图片以创建变化效果# 2. 加载所有图片并调整大小images = []for path in image_paths:try:img = Image.open(path)# 保持原始比例调整宽度aspect_ratio = img.height / img.widthnew_height = int(column_width * aspect_ratio)resized_img = img.resize((column_width, new_height), Image.LANCZOS)images.append(resized_img)except Exception as e:print(f'无法加载图片 {path}: {str(e)}')if not images:raise ValueError('没有有效的图片可以处理')# 3. 初始化列高列表column_heights = [margin] * num_columnsplaced_images = [] # 存储(图片, 位置x, 位置y)# 4. 瀑布流排列算法for img in images:# 寻找最短列min_height = min(column_heights)col_idx = column_heights.index(min_height)# 计算位置坐标x = col_idx * (column_width + margin) + marginy = column_heights[col_idx]# 记录图片位置placed_images.append((img, x, y))# 更新列高度column_heights[col_idx] = y + img.height + margin# 5. 创建画布canvas_width = column_width * num_columns + margin * (num_columns + 1)canvas_height = max(column_heights)collage = Image.new('RGB', (canvas_width, canvas_height), background_color)# 6. 将图片粘贴到画布for img, x, y in placed_images:collage.paste(img, (int(x), int(y)))# 7. 保存结果collage.save(output_path, quality=95)print(f'瀑布流拼贴已保存到 {output_path}')if __name__ == '__main__':create_collage(image_folder='images',output_path='waterfall_collage.jpg',num_columns=8, # 列数column_width=300, # 每列宽度margin=15, # 图片间距background_color=(240, 240, 240) # 浅灰色背景)
运行结果: