如何用Python的PIL库拼接4张不同尺寸图片为2x2布局?
解决PIL拼接2x2不同尺寸图片的问题
你的代码问题在于反复修改img1的尺寸,其他图片的尺寸完全没调整,而且每次修改都会覆盖之前的调整,最后img1只会变成img4的尺寸,根本达不到统一所有图片尺寸的目的。
下面是正确的实现步骤和代码:
步骤说明
- 先确定一个统一的目标尺寸(可以选所有图片中最小的宽高,或者自定义固定尺寸)
- 将四张图片全部调整为这个目标尺寸
- 创建一张足够容纳2x2布局的新画布
- 将调整后的图片分别粘贴到画布对应位置
完整代码示例
from PIL import Image # 打开四张图片(替换成你的图片路径) img1 = Image.open("img1.jpg") img2 = Image.open("img2.jpg") img3 = Image.open("img3.jpg") img4 = Image.open("img4.jpg") # 方法1:选所有图片中最小的宽和高作为统一尺寸 all_widths = [img1.width, img2.width, img3.width, img4.width] all_heights = [img1.height, img2.height, img3.height, img4.height] target_width = min(all_widths) target_height = min(all_heights) # 方法2:自定义固定尺寸(比如都改成300x300) # target_width = 300 # target_height = 300 # 统一所有图片尺寸 img1_resized = img1.resize((target_width, target_height)) img2_resized = img2.resize((target_width, target_height)) img3_resized = img3.resize((target_width, target_height)) img4_resized = img4.resize((target_width, target_height)) # 创建2x2布局的画布:宽度是2倍目标宽,高度是2倍目标高 combined_img = Image.new("RGB", (target_width * 2, target_height * 2)) # 粘贴图片到对应位置 combined_img.paste(img1_resized, (0, 0)) # 左上角 combined_img.paste(img2_resized, (target_width, 0)) # 右上角 combined_img.paste(img3_resized, (0, target_height)) # 左下角 combined_img.paste(img4_resized, (target_width, target_height)) # 右下角 # 保存或显示拼接后的图片 combined_img.save("combined_2x2.jpg") combined_img.show()
关键细节解释
resize()方法需要传入一个元组(宽度, 高度),你之前直接传其他图片的size属性逻辑没问题,但要确保所有图片都调整到同一个尺寸,而不是只改其中一张Image.new()用来创建空白画布,第一个参数是颜色模式(一般用"RGB"),第二个参数是画布的宽高paste()方法的第二个参数是图片左上角的坐标,根据2x2布局计算好位置即可
内容的提问来源于stack exchange,提问作者user20363214
相关产品推荐
相关产品推荐

