python zen导出后图片排版

家里的医生大大,让我把zen导出的图片一张张的排版到ppt或者Adobe Illustrator上。几百张图片。。。卑微的打工人。。。写段脚本吧。

import os
import re
from fpdf import FPDF
import cv2


def get_file(srcpath, patstr):
    fpat = r'(' + patstr + r')' + r'_\S+'
    pattern = re.compile(fpat)
    ids = []
    for file in os.listdir(srcpath):
        presult = pattern.search(file)
        if presult and os.path.isfile(os.path.join(srcpath, file)):
            id = presult.group(1)
            if id not in ids:
                ids.append(id)
    return ids


def format_image_age(srcpath, ids, flags=None):
    if flags is None:
        flags = ['c1+2+3+4', 'c1+2+3', 'c1+2', 'c1', 'c2', 'c3', 'c4']
    image_paths = []
    total_width = 0
    total_height = 0
    for id in ids:
        temp_paths = []
        total_width_tmp = 0
        for flag in flags:
            filename = os.path.join(srcpath, f'{id}_{flag}.jpg')
            if os.path.exists(filename):
                img = cv2.imread(filename)
                temp_paths.append(filename)
                total_width_tmp += img.shape[1]
                total_height = max(total_height, img.shape[0])
        if total_width_tmp > total_width:
            total_width = total_width_tmp
        image_paths.append(temp_paths)
    total_width = total_width * 1.2
    total_height = total_height * 1.2 * len(ids)
    pdf = FPDF(format=(total_width, total_height))
    pdf.add_page()
    pdf.set_auto_page_break(auto=False, margin=15)
    image_width, image_height, _ = img.shape
    margin = 10
    for i in range(len(image_paths)):
        for j in range(len(image_paths[i])):
            x = j * (image_width + margin) + margin
            y = i * (image_height + margin) + margin
            pdf.image(image_paths[i][j], x, y, image_width, image_height)
    name = "_".join(ids)
    pdf_file_name = os.path.join(srcpath, f'{name}.pdf')
    pdf.output(pdf_file_name)
    print(f'PDF save as {pdf_file_name}')


if __name__ == "__main__":
    rootdir = r'D:\IF'
    for root, dirs, files in os.walk(rootdir):
        ids = get_file(root, r'\S+')
        print(root, ids)
        for i in range(0, len(ids), 2):
            oneids = [ids[i]]
            if i + 1 < len(ids):
                oneids.append(ids[i + 1])
            try:
                format_image_age(root, oneids)
            except Exception as e:
                print(e)

 使用的时候修,改一下红线圈出的整两句的参数就行。

workdir = r'F:\2024.1.22'中F:\2024.1.22是原图片的文件夹。get_file(workdir, r'Snap-\d+'),中r'Snap-\d+'图片名的正则(需要懂一点正则才行)。Snap-表示字符"Snap-", \d+表示多个数字字符。r'Snap-\d+'表示全部符合Snap-数字的图片。可以将文件夹和正则表达换成需要的。

结果在原文件夹下生成pdf文件

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值