引言
将powerpoint演示文稿中的形状(幻灯片中的内容元素,包括文本框、图形、图片、图表等)保存为图片是方便内容跨平台分享和再利用的有效手段。利用python,我们可以直接将powerpoint幻灯片中带设计和格式的文本、图片、图形、表格等各种元素直接保存为图片,从而实现在保留原设计和格式的情况下,将其发布在网页或是在其他文档编辑等场景再利用。本文将演示如何使用python保存powerpoint演示文稿中的形状为图像文件。
本文所使用的方法需要用到spire.presentation for python,pypi:pip install spire.presentation。
使用python保存ppt中的所有形状为图像文件
在操作powerpoint演示文稿时,我们可以先使用presentation.loadfromfile()方法从文件载入演示文稿,再使用presentation.slides.get_item()方法获取单个幻灯片或遍历所幻灯片。然后,我们可以遍历通过slide.shapes.saveasimage(shapeindex: int, dpix: int, dpiy: int)方法将形状保存为图像。下面是操作步骤示例:
- 导入所需模块
- 创建
presentation实例。 - 使用
presentation.loadfromfile()方法加载powerpoint演示文稿。 - 使用
presentation.pages.get_item()方法获取一个幻灯片。 - 遍历幻灯片中的形状:
- 使用
slide.shapes.saveasimage()方法将形状保存为图像流。 - 使用
stream.save()方法将图像流保存到文件。
- 使用
代码示例
from spire.presentation import *
# 创建一个 presentation 实例
presentation = presentation()
# 加载一个 powerpoint 文件
presentation.loadfromfile("sample.pptx")
# 获取第四张幻灯片(索引从0开始)
slide = presentation.slides.get_item(4)
# 将形状保存为图片流
for i in range(slide.shapes.count):
# 保存当前形状为指定大小的图片流
imagestream = slide.shapes.saveasimage(i, 256, 256)
# 保存图片到文件
imagestream.save(f"output/shapes/shapetoimage{i}.png")
# 释放资源
presentation.dispose()
结果

用python保存ppt中带格式设计的图片为图像文件
通过直接将形状保存图像文件的方法,我们还可以直接将演示文稿中进行了格式编辑的图片保存图像文件,并保留其格式。我们只需要在将形状保存为图像时,判断其是否为slidepicture实例并保存这些实例。以下是操作步骤示例:
- 导入所需模块
- 创建
presentation实例。 - 使用
presentation.loadfromfile()方法加载powerpoint演示文稿。 - 使用
presentation.pages.get_item()方法获取一个幻灯片。 - 遍历幻灯片中的形状:
- 判断形状是否为
slidepicture实例,如果是则将其保存为图像流。 - 使用
stream.save()方法将图像流保存到图像文件。
- 判断形状是否为
代码示例
from spire.presentation import *
# 创建一个 presentation 实例
presentation = presentation()
# 加载一个 powerpoint 文件
presentation.loadfromfile("sample.pptx")
# 获取第五张幻灯片(索引从0开始)
slide = presentation.slides.get_item(1)
# 遍历幻灯片中的所有形状
i = 0
for shape in slide.shapes:
# 检查形状是否是 slidepicture 类型的对象
if isinstance(shape, slidepicture):
# 保存形状为图片流
shape = shape if isinstance(shape, slidepicture) else none
image = slide.shapes.saveasimage(slide.shapes.indexof(shape), 256, 256)
# 保存图片到文件
image.save(f"output/images/imageshape{i}.png")
i += 1
# 释放资源
presentation.dispose()

本文演示了如何使用python将powerpoint演示文稿中的形状保存图像文件。
到此这篇关于如何使用python保存ppt中的形状为图像文件的文章就介绍到这了,更多相关python保存ppt的形状为图片内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论