【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

背景需求

前期做了苹果、橘子、生梨、葡萄、

教学类-97-04】20251104“生梨”撕贴(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)https://mp.csdn.net/mp_blog/creation/editor/154389802

【教学类-97-06】20251105“葡萄”橡皮泥黏贴(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)https://mp.csdn.net/mp_blog/creation/editor/154497343教学类-97-05】20251104“苹果”撕贴(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)https://mp.csdn.net/mp_blog/creation/editor/154398461教学类-97-03】20251021“橘子”涂色(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)https://mp.csdn.net/mp_blog/creation/editor/153619458

【教学类-97-02】20251020“苹果”涂色(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)https://mp.csdn.net/mp_blog/creation/editor/153626390

再做一串香蕉

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

简笔画,白色背景,香蕉串,没有颜色,正面图

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)



'''
20250802通义万相2.2下载通义照片 copy
Python下载通义万相的图片(存在问题,不能停止,只能默认下载300张,删除多余)
星火讯飞,阿夏
谷歌页面打开通义万相,页面放大到200%
20251003
'''
 
import os,time
import pyautogui
import pyperclip
import re
import win32api
 
 
import win32con
import sys
import ctypes
 
 
import time
 
name='20251107香蕉'
 
# 先打开微信
 
 
num=80
zs=120
# 实际157
 
def minimize_active_window():
    try:
        if sys.platform == 'win32':
 
            # 获取当前活动窗口的句柄
            
            hwnd = ctypes.windll.user32.GetForegroundWindow()
            # 最小化窗口
            ctypes.windll.user32.ShowWindow(hwnd, 6)  # 6 对应 SW_MINIMIZE
            return True
        else:
            print("此功能仅支持Windows系统")
            return False
    except Exception as e:
        print(f"最小化窗口时出错: {e}")
        return False
 
print("程序运行中...")
time.sleep(2)  # 等待2秒,让你有时间切换到VS Code窗口
 
# 尝试最小化活动窗口
if minimize_active_window():
    print("窗口已最小化")
else:
    print("无法最小化窗口")
 
 
 
 
# 读取文件名称和路径
 
path=fr'D:{name}'
 
os.makedirs(path,exist_ok=True)
 
 
for i in range(num,num+zs):
    # 下载按钮     
    pyautogui.moveTo(1569, 302)
 
    pyautogui.click() 
    time.sleep(1)
 
    # 点击有,无水印要包月    
    pyautogui.moveTo(1573, 373)
    pyautogui.click() 
    time.sleep(2)
 
    # 输入图片名称,复制中文内容到剪贴板
    name=path+fr'{i:03}'
    pyperclip.copy(name)
    # 黏贴图片地址
    pyautogui.hotkey('ctrl', 'v')
    time.sleep(1)
 
    pyautogui.press('enter')
#     # 图片显示需要时间
    time.sleep(1)
 
    # 模拟按键“右箭头”
      
    pyautogui.moveTo (989, 628)
    pyautogui.click() 
    time.sleep(2)
    #  'left'(左箭头)
    # 'up'(上箭头)
    # 'down'(下箭头)
 
import sys
import ctypes
import time
 
def minimize_active_window():
    try:
        if sys.platform == 'win32':
            # 获取当前活动窗口的句柄
            hwnd = ctypes.windll.user32.GetForegroundWindow()
            # 最小化窗口
            ctypes.windll.user32.ShowWindow(hwnd, 6)  # 6 对应 SW_MINIMIZE
            return True
        else:
            print("此功能仅支持Windows系统")
            return False
    except Exception as e:
        print(f"最小化窗口时出错: {e}")
        return False
 
print("程序运行中...")
time.sleep(2)  # 等待2秒,让你有时间切换到VS Code窗口
 
# 尝试最小化活动窗口
if minimize_active_window():
    print("窗口已最小化")
else:
    print("无法最小化窗口")

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

生成数量多,可以删除造型奇怪的香蕉(两根、交叉)

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

留下36张

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

不过我没有想好,这个还能用什么材料来黏贴(涂色、撕纸、橡皮泥都用过了)

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

老规矩,做两套样式

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

图案切边,不改变原来的长款比例,背景图统一200*200



'''
香蕉 图片处理,转黑白色,切边,统一大小(背景一样大,头像扥比例,不撑满)
Deepseek,阿夏
20251020
'''
 
import os
from PIL import Image
import numpy as np
 
def convert_to_pure_bw(image_path, output_path, threshold=128):
    """
    将图片转为纯黑白两色(黑色0,0,0和白色255,255,255)
    
    参数:
    image_path: 输入图片路径
    output_path: 输出图片路径
    threshold: 二值化阈值
    """
    try:
        img = Image.open(image_path)
        img = img.convert('L')  # 转为灰度图
        
        # 二值化处理
        binary_img = img.point(lambda x: 0 if x < threshold else 255, '1')
        binary_img = binary_img.convert('RGB')  # 转回RGB模式
        
        # 保存黑白图片
        binary_img.save(output_path)
        print(f"黑白图生成: {os.path.basename(image_path)}")
        return output_path
        
    except Exception as e:
        print(f"处理图片 {image_path} 时出错: {str(e)}")
        return None
 
def crop_transparent_edges(image, margin=0):
    """
    裁剪掉图片的透明边缘,并保留指定的间距
    
    参数:
    image: PIL Image对象(RGBA模式)
    margin: 要保留的间距(磅/像素)
    
    返回:
    裁剪后的PIL Image对象
    """
    # 转换为numpy数组
    data = np.array(image)
    
    # 获取alpha通道
    alpha = data[:, :, 3]
    
    # 找到非透明像素的位置
    non_transparent = np.where(alpha > 0)
    
    if len(non_transparent[0]) == 0:
        # 如果全是透明像素,返回原图
        return image
    
    # 获取非透明区域的边界
    top = np.min(non_transparent[0])
    bottom = np.max(non_transparent[0])
    left = np.min(non_transparent[1])
    right = np.max(non_transparent[1])
    
    # 添加间距
    top = max(0, top - margin)
    bottom = min(image.height - 1, bottom + margin)
    left = max(0, left - margin)
    right = min(image.width - 1, right + margin)
    
    # 裁剪图片
    cropped_image = image.crop((left, top, right + 1, bottom + 1))
    
    return cropped_image
 
def make_background_transparent(bw_image_path, output_path, tolerance=30, margin=0):
    """
    将黑白图片的白色背景变为透明并裁剪透明边缘
    
    参数:
    bw_image_path: 黑白图片路径
    output_path: 输出图片路径
    tolerance: 颜色容差,控制背景识别的灵敏度
    margin: 裁剪后保留的间距(磅/像素)
    """
    # 打开黑白图片并转换为RGBA模式
    with Image.open(bw_image_path) as img:
        # 转换为RGBA模式
        img = img.convert('RGBA')
        
        # 获取图片数据
        data = np.array(img)
        red, green, blue, alpha = data.T
        
        # 创建白色背景掩码:判断像素是否为白色(在容差范围内)
        white_mask = (
            (red >= 255 - tolerance) & (red <= 255) &
            (green >= 255 - tolerance) & (green <= 255) &
            (blue >= 255 - tolerance) & (blue <= 255)
        )
        
        # 将白色背景像素的alpha通道设为0(透明)
        data[white_mask.T] = (255, 255, 255, 0)
        
        # 转换回Image
        result = Image.fromarray(data)
        
        # 裁剪透明边缘并保留间距
        cropped_result = crop_transparent_edges(result, margin)
        
        # 保存结果
        cropped_result.save(output_path, 'PNG')
 
def resize_to_uniform_size(image_path, output_path, target_size=(200, 200)):
    """
    将图片调整为统一大小,保持宽高比,在空白处填充透明
    
    参数:
    image_path: 输入图片路径
    output_path: 输出图片路径
    target_size: 目标尺寸 (宽, 高)
    """
    with Image.open(image_path) as img:
        if img.mode != 'RGBA':
            img = img.convert('RGBA')
        
        # 创建新的透明背景图片
        new_img = Image.new('RGBA', target_size, (255, 255, 255, 0))
        
        # 计算缩放比例,保持宽高比
        img_ratio = img.width / img.height
        target_ratio = target_size[0] / target_size[1]
        
        if img_ratio > target_ratio:
            # 图片较宽,按宽度缩放
            new_width = target_size[0]
            new_height = int(target_size[0] / img_ratio)
        else:
            # 图片较高,按高度缩放
            new_height = target_size[1]
            new_width = int(target_size[1] * img_ratio)
        
        # 缩放图片
        resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
        
        # 计算居中位置
        x = (target_size[0] - new_width) // 2
        y = (target_size[1] - new_height) // 2
        
        # 将缩放后的图片粘贴到新图片上
        new_img.paste(resized_img, (x, y), resized_img)
        
        # 保存结果
        new_img.save(output_path, 'PNG')
 
def process_single_image(image_path, output_path, bw_threshold=128, transparency_tolerance=30, margin=0, target_size=(200, 200)):
    """
    完整处理单张图片:黑白化 → 透明化 → 统一尺寸
    
    参数:
    image_path: 输入图片路径
    output_path: 输出图片路径
    bw_threshold: 黑白化阈值
    transparency_tolerance: 透明化容差
    margin: 裁剪边距
    target_size: 目标尺寸
    """
    try:
        # 步骤1: 转为黑白图片(临时文件)
        temp_bw_path = output_path.replace('.png', '_bw_temp.png')
        bw_path = convert_to_pure_bw(image_path, temp_bw_path, bw_threshold)
        
        if not bw_path:
            return False
        
        # 步骤2: 背景透明化(临时文件)
        temp_transparent_path = output_path.replace('.png', '_trans_temp.png')
        make_background_transparent(bw_path, temp_transparent_path, transparency_tolerance, margin)
        
        # 步骤3: 统一尺寸
        resize_to_uniform_size(temp_transparent_path, output_path, target_size)
        
        # 清理临时文件
        if os.path.exists(temp_bw_path):
            os.remove(temp_bw_path)
        if os.path.exists(temp_transparent_path):
            os.remove(temp_transparent_path)
        
        return True
        
    except Exception as e:
        print(f"处理图片 {image_path} 时出错: {str(e)}")
        # 清理临时文件
        for temp_path in [temp_bw_path, temp_transparent_path]:
            if 'temp_path' in locals() and os.path.exists(temp_path):
                os.remove(temp_path)
        return False
 
def batch_process_images(input_dir, output_dir, bw_threshold=128, transparency_tolerance=30, margin=0, target_size=(200, 200)):
    """
    批量处理文件夹中的所有图片
    
    参数:
    input_dir: 输入文件夹路径
    output_dir: 输出文件夹路径
    bw_threshold: 黑白化阈值
    transparency_tolerance: 透明化容差
    margin: 裁剪边距
    target_size: 目标尺寸
    """
    # 创建输出文件夹(如果不存在)
    os.makedirs(output_dir, exist_ok=True)
    
    # 支持的图片格式
    supported_formats = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff')
    
    # 遍历输入文件夹中的所有文件
    processed_count = 0
    for filename in os.listdir(input_dir):
        # 检查文件是否为支持的图片格式
        if filename.lower().endswith(supported_formats):
            input_path = os.path.join(input_dir, filename)
            # 构建输出文件路径,统一保存为PNG格式
            output_filename = os.path.splitext(filename)[0] + '.png'
            output_path = os.path.join(output_dir, output_filename)
            
            success = process_single_image(
                input_path, output_path, 
                bw_threshold, transparency_tolerance, 
                margin, target_size
            )
            
            if success:
                print(f"已处理: {filename} -> {output_filename}")
                processed_count += 1
            else:
                print(f"处理失败: {filename}")
    
    print(f"批量处理完成!成功处理 {processed_count} 张图片")
 
if __name__ == "__main__":
    # 输入文件夹
    path = r'D:20251107香蕉'
    a = '00原图'
    input_directory = path + fr'{a}'
    
    # 输出文件夹
    output_directory = os.path.join(path, f"{a}黑白透明统一尺寸")
    
    # 检查输入文件夹是否存在
    if not os.path.exists(input_directory):
        print(f"错误: 文件夹 '{input_directory}' 不存在")
    else:
        # 执行批量处理
        batch_process_images(
            input_directory, 
            output_directory, 
            bw_threshold=128,           # 黑白化阈值(0-255)
            transparency_tolerance=30,  # 透明化容差
            margin=0,                   # 裁剪边距
            target_size=(200, 200)      # 统一尺寸
        )
        print("所有图片处理完成!")

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

图案拉宽拉高,统一200*200



'''
香蕉 图片处理,转黑白色,切边,统一大小(背景一样大,图像拉伸撑满)
Deepseek,阿夏
20251106
'''
import os
from PIL import Image
import numpy as np
 
def convert_to_pure_bw(image_path, output_path, threshold=128):
    """
    将图片转为纯黑白两色(黑色0,0,0和白色255,255,255)
    
    参数:
    image_path: 输入图片路径
    output_path: 输出图片路径
    threshold: 二值化阈值
    """
    try:
        img = Image.open(image_path)
        img = img.convert('L')  # 转为灰度图
        
        # 二值化处理
        binary_img = img.point(lambda x: 0 if x < threshold else 255, '1')
        binary_img = binary_img.convert('RGB')  # 转回RGB模式
        
        # 保存黑白图片
        binary_img.save(output_path)
        print(f"黑白图生成: {os.path.basename(image_path)}")
        return output_path
        
    except Exception as e:
        print(f"处理图片 {image_path} 时出错: {str(e)}")
        return None
 
def crop_transparent_edges(image, margin=0):
    """
    裁剪掉图片的透明边缘,并保留指定的间距
    
    参数:
    image: PIL Image对象(RGBA模式)
    margin: 要保留的间距(磅/像素)
    
    返回:
    裁剪后的PIL Image对象
    """
    # 转换为numpy数组
    data = np.array(image)
    
    # 获取alpha通道
    alpha = data[:, :, 3]
    
    # 找到非透明像素的位置
    non_transparent = np.where(alpha > 0)
    
    if len(non_transparent[0]) == 0:
        # 如果全是透明像素,返回原图
        return image
    
    # 获取非透明区域的边界
    top = np.min(non_transparent[0])
    bottom = np.max(non_transparent[0])
    left = np.min(non_transparent[1])
    right = np.max(non_transparent[1])
    
    # 添加间距
    top = max(0, top - margin)
    bottom = min(image.height - 1, bottom + margin)
    left = max(0, left - margin)
    right = min(image.width - 1, right + margin)
    
    # 裁剪图片
    cropped_image = image.crop((left, top, right + 1, bottom + 1))
    
    return cropped_image
 
def make_background_transparent(bw_image_path, output_path, tolerance=30, margin=0):
    """
    将黑白图片的白色背景变为透明并裁剪透明边缘
    
    参数:
    bw_image_path: 黑白图片路径
    output_path: 输出图片路径
    tolerance: 颜色容差,控制背景识别的灵敏度
    margin: 裁剪后保留的间距(磅/像素)
    """
    # 打开黑白图片并转换为RGBA模式
    with Image.open(bw_image_path) as img:
        # 转换为RGBA模式
        img = img.convert('RGBA')
        
        # 获取图片数据
        data = np.array(img)
        red, green, blue, alpha = data.T
        
        # 创建白色背景掩码:判断像素是否为白色(在容差范围内)
        white_mask = (
            (red >= 255 - tolerance) & (red <= 255) &
            (green >= 255 - tolerance) & (green <= 255) &
            (blue >= 255 - tolerance) & (blue <= 255)
        )
        
        # 将白色背景像素的alpha通道设为0(透明)
        data[white_mask.T] = (255, 255, 255, 0)
        
        # 转换回Image
        result = Image.fromarray(data)
        
        # 裁剪透明边缘并保留间距
        cropped_result = crop_transparent_edges(result, margin)
        
        # 保存结果
        cropped_result.save(output_path, 'PNG')
 
def resize_to_exact_size(image_path, output_path, target_size=(200, 200)):
    """
    将图片拉伸到精确的200×200尺寸
    
    参数:
    image_path: 输入图片路径
    output_path: 输出图片路径
    target_size: 目标尺寸 (宽, 高)
    """
    with Image.open(image_path) as img:
        if img.mode != 'RGBA':
            img = img.convert('RGBA')
        
        # 直接拉伸到目标尺寸
        resized_img = img.resize(target_size, Image.Resampling.LANCZOS)
        
        # 保存结果
        resized_img.save(output_path, 'PNG')
 
def process_single_image(image_path, output_path, bw_threshold=128, transparency_tolerance=30, margin=0, target_size=(200, 200)):
    """
    完整处理单张图片:黑白化 → 透明化 → 精确拉伸到200×200
    
    参数:
    image_path: 输入图片路径
    output_path: 输出图片路径
    bw_threshold: 黑白化阈值
    transparency_tolerance: 透明化容差
    margin: 裁剪边距
    target_size: 目标尺寸
    """
    try:
        # 步骤1: 转为黑白图片(临时文件)
        temp_bw_path = output_path.replace('.png', '_bw_temp.png')
        bw_path = convert_to_pure_bw(image_path, temp_bw_path, bw_threshold)
        
        if not bw_path:
            return False
        
        # 步骤2: 背景透明化(临时文件)
        temp_transparent_path = output_path.replace('.png', '_trans_temp.png')
        make_background_transparent(bw_path, temp_transparent_path, transparency_tolerance, margin)
        
        # 步骤3: 精确拉伸到目标尺寸
        resize_to_exact_size(temp_transparent_path, output_path, target_size)
        
        # 清理临时文件
        if os.path.exists(temp_bw_path):
            os.remove(temp_bw_path)
        if os.path.exists(temp_transparent_path):
            os.remove(temp_transparent_path)
        
        return True
        
    except Exception as e:
        print(f"处理图片 {image_path} 时出错: {str(e)}")
        # 清理临时文件
        for temp_path in [temp_bw_path, temp_transparent_path]:
            if 'temp_path' in locals() and os.path.exists(temp_path):
                os.remove(temp_path)
        return False
 
def batch_process_images(input_dir, output_dir, bw_threshold=128, transparency_tolerance=30, margin=0, target_size=(200, 200)):
    """
    批量处理文件夹中的所有图片
    
    参数:
    input_dir: 输入文件夹路径
    output_dir: 输出文件夹路径
    bw_threshold: 黑白化阈值
    transparency_tolerance: 透明化容差
    margin: 裁剪边距
    target_size: 目标尺寸
    """
    # 创建输出文件夹(如果不存在)
    os.makedirs(output_dir, exist_ok=True)
    
    # 支持的图片格式
    supported_formats = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff')
    
    # 遍历输入文件夹中的所有文件
    processed_count = 0
    for filename in os.listdir(input_dir):
        # 检查文件是否为支持的图片格式
        if filename.lower().endswith(supported_formats):
            input_path = os.path.join(input_dir, filename)
            # 构建输出文件路径,统一保存为PNG格式
            output_filename = os.path.splitext(filename)[0] + '.png'
            output_path = os.path.join(output_dir, output_filename)
            
            success = process_single_image(
                input_path, output_path, 
                bw_threshold, transparency_tolerance, 
                margin, target_size
            )
            
            if success:
                print(f"已处理: {filename} -> {output_filename}")
                processed_count += 1
            else:
                print(f"处理失败: {filename}")
    
    print(f"批量处理完成!成功处理 {processed_count} 张图片")
 
if __name__ == "__main__":
    # 输入文件夹
    path = r'D:20251107香蕉'
    a = '00原图'
    input_directory = path + fr'{a}'
    
    # 输出文件夹
    output_directory = os.path.join(path, f"{a}黑白透明拉伸")
    
    # 检查输入文件夹是否存在
    if not os.path.exists(input_directory):
        print(f"错误: 文件夹 '{input_directory}' 不存在")
    else:
        # 执行批量处理
        batch_process_images(
            input_directory, 
            output_directory, 
            bw_threshold=128,           # 黑白化阈值(0-255)
            transparency_tolerance=30,  # 透明化容差
            margin=0,                   # 裁剪边距
            target_size=(200, 200)      # 精确拉伸到200×200
        )
        print("所有图片处理完成!所有图片已拉伸到200×200像素")

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

两种图片都做成PDF六图



 
'''
把香蕉做成一页6张(两种)
AI对话大师,阿夏
20251107
'''
 
import random
import math
from PIL import Image, ImageDraw, ImageFont
import os
import time
from docx import Document
from docx.shared import Cm
from docx2pdf import convert
from PyPDF2 import PdfMerger
import shutil
 
# 测试图片59张
path = r'D:20251107香蕉'
# 格子一共有几个
sl = 6
for names in [f'00原图黑白透明统一尺寸',f'00原图黑白透明拉伸']:
    input_path = path + fr'{names}'
    mb = '香蕉'
    # 表格有2列
    L = 2
    # 高度和宽度是多少厘米
    h = 9.35
    # w = 9.35
 
    def check_and_repair_image(image_path):
        """检查并修复图片文件"""
        try:
            with Image.open(image_path) as img:
                img.verify()  # 验证图片完整性
            return True
        except (IOError, SyntaxError, Exception) as e:
            print(f"图片文件损坏: {image_path}, 错误: {e}")
            return False
 
    def get_valid_image_files(input_path):
        """获取有效的图片文件列表"""
        valid_files = []
        for file in os.listdir(input_path):
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                file_path = os.path.join(input_path, file)
                if check_and_repair_image(file_path):
                    valid_files.append(file_path)
                else:
                    print(f"跳过损坏的图片: {file}")
        return valid_files
 
    print('----1、检查图片文件------------')
    file_paths = get_valid_image_files(input_path)
    print(f"找到 {len(file_paths)} 张有效图片")
 
    if len(file_paths) == 0:
        print("没有找到有效的图片文件,程序退出")
        exit()
 
    grouped_files = [file_paths[i:i+sl] for i in range(0, len(file_paths), sl)]
    print(f"分成 {len(grouped_files)} 组")
 
    print('----2、创建临时文件夹------------')
    new_folder = path + r'零时文件夹'
    if os.path.exists(new_folder):
        shutil.rmtree(new_folder)
    os.makedirs(new_folder, exist_ok=True)
 
    print('----3、插入docx,制作pdf------------')
 
    def create_document_with_images(group, group_index):
        """在已有模板中插入图片"""
        try:
            # 检查模板文件是否存在
            template_path = path + fr'{mb}.docx'
            if not os.path.exists(template_path):
                print(f"模板文件不存在: {template_path}")
                return False
            
            # 打开模板文档
            doc = Document(template_path)
            
            # 检查文档中是否有表格
            if len(doc.tables) == 0:
                print("模板文档中没有找到表格")
                return False
            
            # 获取第一个表格
            table = doc.tables[0]
            
            # 计算表格的行列数
            rows = len(table.rows)
            cols = len(table.columns)
            total_cells = rows * cols
            
            print(f"表格大小: {rows}行 x {cols}列, 共{total_cells}个单元格")
            
            # 遍历每个单元格,并插入图片
            for cell_index, image_file in enumerate(group):
                if not image_file or not os.path.exists(image_file):
                    print(f"图片文件不存在: {image_file}")
                    continue
                
                # 如果单元格索引超出表格范围,跳过
                if cell_index >= total_cells:
                    print(f"图片数量超过表格容量,跳过第{cell_index + 1}张图片")
                    break
                
                # 计算行和列的位置
                row = cell_index // cols
                col = cell_index % cols
                
                # 获取单元格
                cell = table.cell(row, col)
                
                # 清除单元格内容
                for paragraph in cell.paragraphs:
                    p = paragraph._element
                    p.getparent().remove(p)
                
                # 添加新段落并插入图片
                cell_paragraph = cell.add_paragraph()
                cell_paragraph.alignment = 1  # 居中对齐
                
                run = cell_paragraph.add_run()
                try:
                    run.add_picture(image_file, height=Cm(h))
                    print(f"成功插入图片到表格位置({row+1},{col+1}): {os.path.basename(image_file)}")
                except Exception as e:
                    print(f"插入图片失败 {image_file}: {e}")
                    continue
            
            # 保存Word文档
            docx_path = os.path.join(new_folder, f'{group_index + 1:03d}.docx')
            doc.save(docx_path)
            print(f"创建文档成功: {group_index + 1:03d}.docx")
            return True
            
        except Exception as e:
            print(f"创建文档失败 组{group_index + 1}: {e}")
            return False
 
    # 处理每一组图片
    success_count = 0
    for group_index, group in enumerate(grouped_files):
        if create_document_with_images(group, group_index):
            success_count += 1
 
    print(f"成功创建 {success_count} 个Word文档")
 
    print('----4、转换为PDF------------')
    pdf_files = []
    if success_count > 0:
        # 获取所有DOCX文件并按数字排序
        docx_files = [f for f in os.listdir(new_folder) if f.endswith('.docx')]
        docx_files.sort()
        
        for docx_file in docx_files:
            docx_path = os.path.join(new_folder, docx_file)
            pdf_path = docx_path.replace('.docx', '.pdf')
            try:
                convert(docx_path, pdf_path)
                pdf_files.append(pdf_path)
                print(f"转换成功: {docx_file} -> {os.path.basename(pdf_path)}")
                time.sleep(0.5)  # 短暂等待避免冲突
            except Exception as e:
                print(f"转换失败 {docx_file}: {e}")
 
    print('----5、合并PDF------------')
    if pdf_files:
        # 按文件名排序
        pdf_files.sort()
        
        # 合并PDF
        merger = PdfMerger()
        for pdf_file in pdf_files:
            try:
                merger.append(pdf_file)
                print(f"添加PDF: {os.path.basename(pdf_file)}")
            except Exception as e:
                print(f"添加PDF失败 {pdf_file}: {e}")
        
        # 保存合并后的PDF
        pdf_output_path = path + fr'{mb[:2]}{names[2:4]}{names}{mb}(A4一页{sl}张)共{len(file_paths)}图 .pdf'
        try:
            merger.write(pdf_output_path)
            merger.close()
            print(f"PDF合并完成: {pdf_output_path}")
        except Exception as e:
            print(f"PDF合并失败: {e}")
    else:
        print("没有可合并的PDF文件")
 
    print('----6、清理临时文件------------')
    try:
        shutil.rmtree(new_folder)
        print("临时文件夹已清理")
    except Exception as e:
        print(f"清理临时文件夹失败: {e}")
 
    print('----程序执行完成------------')

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

图案变形

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

图案原尺寸

【教学类-97-07】20251105“香蕉”(小班主题《苹果与橘子》)

© 版权声明

相关文章

暂无评论

none
暂无评论...