python如何将多张图片批量插入PPT中?

python如何将多张图片批量插入PPT中?

  • 第一步 获取图片
  • 第二步 生成PPT

第一步 获取图片

批量获取第一类图片

import shutil
import easygui as g
import os

# 检查 ./SourceImage 目录是否存在,不存在则创建它
if (not (os.path.exists( r"C:\Users\Public\Documents\Word" ))):
    os.mkdir( r"C:\Users\Public\Documents\Word" )
if (not (os.path.exists( r"C:\Users\Public\Documents\Word1" ))):
    os.mkdir( r"C:\Users\Public\Documents\Word1" )
if (not (os.path.exists( r"C:\Users\Public\Documents\res" ))):
    os.mkdir( r"C:\Users\Public\Documents\res" )
path = g.diropenbox()
g = os.walk(path)
for path, dir_list, file_list in g:
    for file_name in file_list:
        if "WholeCoreViewer.png" in os.path.join(path, file_name):
            picpath2 = os.path.join(path, file_name)
            print("正在复制... %s " % picpath2)
            new_name = picpath2.split('\\')
            new_name2 = new_name[-1]
            # print(new_name2)

            shutil.copy(picpath2, os.path.join(r'C:\Users\Public\Documents\Word1', new_name2))

批量获取第二类图片(第二类图需要压缩)

import shutil
import easygui as g
import base64
import io
import os
from PIL import Image
from PIL import ImageFile


copypath = r'C:\Users\Public\Documents\Word'
path = g.diropenbox()
g = os.walk(path)
a = []
for path, dir_list, file_list in g:
    for file_name in file_list:
        if ".JPG" in os.path.join(path, file_name):
            # print(path)
            # print( file_list )
            for i in file_list:
                if ".JPG" in i:
                    f = i
                    a.append(f)
            path_name1 =path.replace("\\", "_")
            path_name2 = path_name1.replace(":", "_")
            path_name3 =path_name2.replace(". ", "_")
            # print(os.path.join(path, file_name))
            picpath = os.path.join(path, file_name)
            file_name = "\\%s_%s" % (path_name3, a[0])
            picpath2 = os.path.join(path, copypath + file_name)
            picpath3 =picpath2.replace(".JPG", ".JPEG")
            print("正在复制... %s " % picpath3)
            shutil.copy(picpath, picpath3)

# 压缩图片文件
def compress_image(outfile, mb=190, quality=85, k=0.9):
    """不改变图片尺寸压缩到指定大小
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标,KB   190kb
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址,压缩文件大小
    """
    o_size = os.path.getsize( outfile ) // 1024
    print( "正在压缩%s图片,从%skb到%skb" % (picpath3,o_size, mb))
    if o_size <= mb:
        print( outfile )
        print( outfile.split( '.' )[0] + '.png' )
        return outfile
    ImageFile.LOAD_TRUNCATED_IMAGES = True
    while o_size > mb:
        im = Image.open( outfile )
        x, y = im.size
        out = im.resize( (int( x * k ), int( y * k )), Image.ANTIALIAS )
        try:
            out.save( outfile, quality=quality )
        except Exception as e:
            print( e )
            break
        o_size = os.path.getsize( outfile ) // 1024
    return outfile

# 压缩base64的图片
def compress_image_bs4(b64, mb=190, k=0.9):
    """不改变图片尺寸压缩到指定大小
    :param outfile: 压缩文件保存地址
    :param mb: 压缩目标,KB
    :param step: 每次调整的压缩比率
    :param quality: 初始压缩比率
    :return: 压缩文件地址,压缩文件大小
    """
    f = base64.b64decode( b64 )
    with io.BytesIO( f ) as im:
        o_size = len( im.getvalue() ) // 1024
        if o_size <= mb:
            return b64
        im_out = im
        while o_size > mb:
            img = Image.open( im_out )
            x, y = img.size
            out = img.resize( (int( x * k ), int( y * k )), Image.ANTIALIAS )
            im_out.close()
            im_out = io.BytesIO()
            out.save( im_out, 'jpeg' )
            o_size = len( im_out.getvalue() ) // 1024
        b64 = base64.b64encode( im_out.getvalue() )
        im_out.close()
        return str( b64, encoding='utf8' )

# 将指定文件夹filePath下的 文件地址 和 子文夹下的文件地址 塞进picuture_list列表中
def read_file(filePath):
    picuture_list = []
    for dirpath, dirnames, filenames in os.walk( filePath ):
        path = [os.path.join( dirpath, names ) for names in filenames]
        picuture_list.extend( path )
    return picuture_list
# jpg格式转为png格式
def jpg_to_png(file):
    if file.endswith( 'JPG' ) or file.endswith( 'jpg' ):
        # 要指明重命名之后的路径
        src = os.path.join( copypath, file )
        r_name = file.split( '.' )[0] + '.png'
        dct = os.path.join( copypath, r_name )
        os.rename( src, dct )

outfile = read_file( copypath )
for file in outfile:
    compress_image(file)   #先压缩图片
    jpg_to_png( file )  # 再将图片转为PNG格式
    

第二步 生成PPT

# 加载库
from pptx.util import Cm, Inches, Pt
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor
import os
from pptx import Presentation

# 设置路径

work_path = r'C:\Users\Public\Documents\res'
os.chdir(work_path)

# 实例化 ppt 文档对象
prs = Presentation()
# # 设置幻灯片尺寸,16:9
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)

# 插入幻灯片
rootdir = r'C:\Users\Public\Documents\Word'
rootdir1 = r'C:\Users\Public\Documents\Word1'

list = os.listdir(rootdir)
list1 = os.listdir(rootdir1)  # 列出文件夹下所有的目录与文件
print(list)  # ['喷碳.jpeg', '岩心烘箱.jpeg', '显微镜.jpeg']
print(list1)  # ['WYD1#_1_1_100cm.WholeCoreViewer.png']

# 添加图片
i = 0
j = 0
while i < len(list1):
    img_name1 = rootdir + '\\' + list[i]
    img_name2 = rootdir1 + '\\' + list1[j]
    print(img_name1)
    print(img_name2)

    blank_slide = prs.slide_layouts[6]
    slide_1 = prs.slides.add_slide( blank_slide )

    a = slide_1.shapes.add_picture( image_file=img_name1,
                               left=Inches(0.1),
                               top=Inches(2),
                               width=Inches(8.2),
                               height=Inches(5.8))
    a.rotation = (90.00)  # 
    
    a = slide_1.shapes.add_picture( image_file=r'C:\Users\Public\Documents\Clipboard2.png',
                               left=Inches(8),
                               top=Inches(0),
                               width=Inches(5.5),
                               height=Inches(1))
    # 以上放置比例标尺的截图
    slide_1.shapes.add_picture( image_file=img_name2,
                                left=Inches( 8),
                                top=Inches( 0.8 ),
                                width=Inches( 5.5 ),
                                height=Inches( 8.2) )

    textbox= slide_1.shapes.add_textbox(left=Inches(0.1),
                                        top=Inches(0),
                                        width=Inches(6),
                                        height=Inches(1))

    tf = textbox.text_frame
    para = tf.add_paragraph()    # 添加段落
    para.text = "%s" % list1[i]
    para.alignment = PP_ALIGN.LEFT  # 居中
    ## 设置字体
    font = para.font
    font.size = Pt(20)    # 大小
    font.name = 'Arial'    # 字体
    font.color.rgb = RGBColor(255, 0, 0)  # 红色

    i += 1
    j += 1

# 保存 ppt
prs.save('result.pptx')


你可能感兴趣的:(我的应用,python,pycharm,爬虫)