为了实现将选中的任意图片,扩展为N*N个 Gird布局的图片,写了如下代码
实现效果
原图
原图
生成2*2图片效果
2*2效果
生成4*4图片效果
4*4效果
完整代码
from PIL import Image
import os
def create_image_grid(input_image_path, output_image_path, grid_size):
# 打开原始图像
original_image = Image.open(input_image_path)
# 图像的宽度和高度
width, height = original_image.size
# 新图像的尺寸
new_width = width * grid_size
new_height = height * grid_size
# 创建一个新的空白图像
new_image = Image.new('RGB', (new_width, new_height))
# 将原始图像复制到新图像的各个位置
for i in range(grid_size):
for j in range(grid_size):
new_image.paste(original_image, (i * width, j * height))
# 保存新图像
new_image.save(output_image_path)
print(f"新图像已保存为: {output_image_path}")
# 使用示例
input_image_path = input("请输入要处理的图片路径(包括文件名和扩展名):")
output_image_path = "output_image.jpg" # 输出文件名
grid_size = int(input("请输入矩阵大小N(例如4表示4x4矩阵):"))
# 检查输入文件是否存在
if os.path.exists(input_image_path):
create_image_grid(input_image_path, output_image_path, grid_size)
else:
print("输入的文件路径不存在,请检查后重试。")