当前位置:首页>python>实用Python代码3:图片拼接

实用Python代码3:图片拼接

  • 2026-09-27 03:54:58
实用Python代码3:图片拼接

图片拼接是社交、学习、办公的高频需求,但主流工具功能冗余、广告繁多且需付费。本款基于Python开发的轻量化图片拼接小程序摒弃了多余的附加功能,聚焦图片拼接核心需求,依托成熟的图像处理库,实现了不同格式图片同时批量导入、尺寸自适应调整、自定义行列数(默认3列)、高清无损导出等实用功能,兼具简洁性与实用性,代码精简、运行流畅,无需复杂安装配置,新手也能快速上手。相较于商用工具,该小程序免费开源、操作灵活,可根据需求自主调整参数,完美适配学生、办公人群的日常使用场景,为轻量化图片处理提供了高效便捷的全新解决方案。

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("图片拼接完成,按回车键退出......")

样图:

喜欢请评论、关注、点赞、收藏和转发❤️。关注+私信,可索取打包好的 exe 可执行程序,无需安装 Python 及依赖库,双击直接运行,有空必回。

最新文章

随机文章