本文所使用的 CodeBuddy 免费下载链接:腾讯云代码助手 CodeBuddy - AI 时代的智能编程伙伴

前言

在上一章节中我们已经实现了图片下载的脚本了, 本篇文章我们主要实现的是将多张图片合并成一张图片,并可以选择生成不同风格的图片。通过本教程,你将学会如何利用AI助手快速实现图片合成功能,打造属于自己的图片处理工具。

获取图片教程速通车: https://cloud.tencent.com/developer/article/2522030

确定目标

同样我们打开 CodeBuddy, 在Chat 模式下输入提示词

在美女图片的文件夹下存在多张图片,需求如下:
1.将文件夹下的图片合成一张图片
2.可以设置不同风格的图片, 给出选择

CodeBuddy提示词输入

复制代码运行程序

我们将 CodeBuddy 生成的py代码复制到pycharm 中运行该程序, 效果如下图所示

初次运行效果

让我比较惊讶, 我只想要一个选择的目录需要提前设定好即可, 输出的目录也是在当前的文件中,但是CodeBuddy 给了我一个可视化的编辑界面。按照可视化界面的提示我们输入相关内容,点击生成,查看效果

可视化界面

合成图片如下图所示

初次合成效果

但是这种并不是我需要的,因此代码还需修改, 我们重新编写自己的需求给到CodeBuddy,如下图所示

修改需求

等待代码生成完成之后我们运行代码查看效果
代码执行效果如下

代码执行效果

多风格合成效果展示

通过我们的代码,可以实现四种不同风格的图片合成效果,每种风格都有其独特的视觉表现:

艺术拼贴风格

这种风格将图片以随机角度和位置排列,创造出充满艺术感的拼贴效果,适合创意展示。

艺术拼贴效果

网格布局风格

网格布局将图片整齐排列成矩阵形式,清晰有序,适合展示产品集合或照片墙。

网格布局效果

水平布局风格

水平布局将图片横向排列,适合展示时间线或横幅设计。

水平布局效果

垂直布局风格

垂直布局将图片纵向排列,适合长图文设计或手机端浏览。

垂直布局效果

完整代码

最终代码如下:

import os
import math
from PIL import Image
import random


def combine_images(input_folder, output_folder, base_filename="combined", max_width=2000, spacing=10):
    """
    将多张图片合成为一张图片,生成所有风格的合成图

    参数:
        input_folder: 输入图片文件夹路径
        output_folder: 输出文件夹路径
        base_filename: 输出文件基础名称
        max_width: 输出图片最大宽度
        spacing: 图片间距
    """
    # 获取所有图片文件
    image_files = []
    for f in os.listdir(input_folder):
        if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
            image_files.append(os.path.join(input_folder, f))

    if not image_files:
        print("错误: 没有找到图片文件")
        return False

    # 打开所有图片并调整大小
    images = []
    for img_file in image_files:
        try:
            img = Image.open(img_file)
            # 统一调整为相同宽度,保持比例
            base_img_width = max_width // 4  # 基础宽度
            w_percent = (base_img_width / float(img.size[0]))
            h_size = int((float(img.size[1]) * float(w_percent)))
            img = img.resize((base_img_width, h_size), Image.LANCZOS)
            images.append(img)
        except Exception as e:
            print(f"警告: 无法处理图片 {img_file}: {e}")

    if not images:
        print("错误: 没有有效的图片可以处理")
        return False

    # 确保输出目录存在
    os.makedirs(output_folder, exist_ok=True)

    # 定义所有风格
    styles = {
        'grid': "网格布局",
        'vertical': "垂直布局",
        'horizontal': "水平布局",
        'collage': "艺术拼贴"
    }

    # 为每种风格生成合成图
    for style_code, style_name in styles.items():
        output_path = os.path.join(output_folder, f"{base_filename}_{style_code}.jpg")
        print(f"正在生成 {style_name} 风格的合成图...")

        if style_code == 'grid':
            # 网格布局
            cols = math.ceil(math.sqrt(len(images)))
            rows = math.ceil(len(images) / cols)
            img_width = images[0].width
            img_height = images[0].height

            total_width = cols * img_width + (cols - 1) * spacing
            total_height = rows * img_height + (rows - 1) * spacing

            result = Image.new('RGB', (total_width, total_height), (255, 255, 255))

            for i, img in enumerate(images):
                row = i // cols
                col = i % cols
                x = col * (img_width + spacing)
                y = row * (img_height + spacing)
                result.paste(img, (x, y))

        elif style_code == 'vertical':
            # 垂直布局
            total_width = max(img.width for img in images)
            total_height = sum(img.height for img in images) + (len(images) - 1) * spacing

            result = Image.new('RGB', (total_width, total_height), (255, 255, 255))

            y_offset = 0
            for img in images:
                result.paste(img, ((total_width - img.width) // 2, y_offset))
                y_offset += img.height + spacing

        elif style_code == 'horizontal':
            # 水平布局
            total_width = sum(img.width for img in images) + (len(images) - 1) * spacing
            total_height = max(img.height for img in images)

            result = Image.new('RGB', (total_width, total_height), (255, 255, 255))

            x_offset = 0
            for img in images:
                result.paste(img, (x_offset, (total_height - img.height) // 2))
                x_offset += img.width + spacing

        elif style_code == 'collage':
            # 艺术拼贴风格
            total_width = max_width
            total_height = int(total_width * 1.5)
            result = Image.new('RGB', (total_width, total_height), (250, 250, 250))

            for img in images:
                # 随机旋转角度
                angle = random.randint(-15, 15)
                rotated_img = img.rotate(angle, expand=True)

                # 随机位置
                x = random.randint(0, max(1, total_width - rotated_img.width))
                y = random.randint(0, max(1, total_height - rotated_img.height))

                # 随机透明度
                if random.random() > 0.7:
                    rotated_img = rotated_img.convert("RGBA")
                    rotated_img.putalpha(random.randint(150, 220))
                    result.paste(rotated_img, (x, y), rotated_img)
                else:
                    result.paste(rotated_img, (x, y))

        # 保存结果
        try:
            result.save(output_path, quality=95)
            print(f"成功: {style_name} 风格合成图已保存到 {output_path}")
        except Exception as e:
            print(f"错误: 保存 {style_name} 风格合成图失败: {e}")

    return True


if __name__ == "__main__":
    # 在这里设置你的输入和输出目录
    INPUT_FOLDER = "./美女图片"  # 替换为你的图片文件夹路径
    OUTPUT_FOLDER = "./合成结果"  # 替换为你想要的输出文件夹路径

    # 执行合成
    print("=== 开始图片合成 ===")
    combine_images(INPUT_FOLDER, OUTPUT_FOLDER)
    print("=== 图片合成完成 ===")

总结与思考

通过本次实践,我们成功利用CodeBuddy实现了一个功能强大的图片合成工具,具有以下特点:

  1. 多样化风格选择:提供了四种不同的布局风格(网格、垂直、水平和艺术拼贴),满足不同场景的需求
  2. 智能图片处理:自动调整图片大小,保持比例,确保合成效果美观
  3. 错误处理机制:代码中包含了完善的错误处理,确保程序稳定运行
  4. 简单易用:只需设置输入和输出目录,一键生成所有风格的合成图

通过简单的自然语言描述,CodeBuddy能够理解我们的需求并生成完整可用的代码。当初始代码不完全符合需求时,我们可以通过进一步的对话来优化和完善,最终得到满意的结果。
通过AI辅助编程,即使是编程新手也能快速实现复杂功能,大大提高了开发效率。希望这个教程能够帮助你了解CodeBuddy编程助手的使用方法,并在自己的项目中灵活应用。


全栈若城
6 声望2 粉丝