批量把漫画图片转化为PDF

查看 69|回复 5
作者:aichiyu   
[Asm] 纯文本查看 复制代码from PIL import Image
import os
import gc
def images_to_pdf(image_dir):
    # 遍历所有子目录
    for root, dirs, files in os.walk(image_dir):
        image_files = [f for f in files if f.lower().endswith(('png', 'jpg', 'jpeg', 'bmp', 'gif'))]
        image_files.sort()  # 可选:对文件进行排序,以确保PDF中的页面顺序
        # 如果当前目录中没有图片文件,则跳过
        if not image_files:
            continue
        # 生成PDF文件名,以子目录名称命名
        subdir_name = os.path.basename(root)
        parent_dir = os.path.dirname(root)
        output_pdf = os.path.join(parent_dir, f'{subdir_name}.pdf')
        # 检查PDF是否已经存在
        if os.path.exists(output_pdf):
            print(f"PDF文件已存在,跳过:{output_pdf}")
            continue
        # 打开所有图片文件,并将其转换为RGB模式
        images = []
        for file in image_files:
            img_path = os.path.join(root, file)
            with Image.open(img_path) as img:
                img = img.convert('RGB')
                images.append(img.copy())  # 复制图像对象,释放原始图像资源
                img.close()  # 关闭原始图像文件
            # 手动进行垃圾回收
            gc.collect()
        # 确保输出目录存在
        os.makedirs(parent_dir, exist_ok=True)
        # 保存图片为PDF文件
        if images:
            images[0].save(output_pdf, save_all=True, append_images=images[1:])
            print(f"PDF文件已保存到 {output_pdf}")
        else:
            print(f"没有找到图片文件在目录 {root}")
        # 手动进行垃圾回收
        images.clear()
        gc.collect()
# 示例使用
image_directory = input('请输入漫画目录地址: ')
images_to_pdf(image_directory)

文件, 图片

weimeng555   

感谢大佬分享好东西,羡慕程序员,能否做成一个应用程序呢?
shenhuen10   

感谢大神,正好搞点漫画在车上看
雾都孤尔   

支持原创,感谢分享。
tfl1   

已把大佬的代码转为应用程序,希望大家可以支持下
https://www.123pan.com/s/fw4wjv-rpQl.html  提取码:52pj
hanbazhen   


tfl1 发表于 2024-6-14 15:59
已把大佬的代码转为应用程序,希望大家可以支持下
https://www.123pan.com/s/fw4wjv-rpQl.html ...

哥们是什么软件转的?求教
您需要登录后才可以回帖 登录 | 立即注册

返回顶部