本简短教程重点介绍如何在 Python 中将 PNG 转换为 PowerPoint 幻灯片。它包含所有配置信息、逐步过程和可运行的示例代码,用于使用 Python 在 PPTX 中插入图像**。该应用程序可用于配置了 .NET Core 和 Python 的任何操作系统,如 Windows、Linux 或 macOS。
在 Python 中在 PPTX 中插入图像的步骤
- 将您的 IDE 配置为 通过 .NET 使用 Aspose.Slides for Python
- 在项目中添加对 aspose.pydrawing 和 aspose.slides 命名空间的引用,以使用 Python 在 PPTX 中插入图像
- 使用 Presentation 类对象创建一个空的默认演示文稿并访问新创建的演示文稿的第一张默认幻灯片
- 从磁盘读取源 PNG 图像作为字节,并将其添加到演示文稿的图像集合中
- 使用添加的在所选幻灯片的形状集合中插入相框
- 在 Python 中使用 save 方法将 PNG 转换为 PPTX
上述步骤指导在 Python* 中开发 *PNG 到 PPTX 转换器,其中会生成包含默认幻灯片集合和图像集合的新演示文稿。源图像作为字节数组从磁盘加载,作为相框添加到第一个幻灯片形状集合中,最后,带有图像的演示文稿保存在磁盘上。
在 Python 中在 PPTX 中添加图像的代码
import aspose.pydrawing as drawing | |
import aspose.slides as slides | |
filepath = "C://Data//" | |
# Applying the linence for Aspose.Slides | |
slidesLicense = slides.License() | |
slidesLicense.set_license(filepath + "Aspose.Total.lic") | |
# Generate a default empty presentation using Presentation class object | |
with slides.Presentation() as samplePres: | |
# Access the first slide of the newly created presentation | |
slideForPng = samplePres.slides[0] | |
with open(filepath + "sample.png", "rb") as binary_file: | |
#Read the whole file at once | |
imageData = binary_file.read() | |
# Add the source image inside the images collection of the presentation | |
imageForSlide = samplePres.images.add_image(imageData) | |
# Add the picture frame in the shapes collection of the slide | |
slideForPng.shapes.add_picture_frame(slides.ShapeType.RECTANGLE, 20, 20, 90, 90, imageForSlide) | |
# Save the presentation with image on the disk | |
samplePres.save(filepath + "PresentationWithImage.pptx", slides.export.SaveFormat.PPTX) | |
print("Completed") |
在使用此功能在 Python 中将 PNG 转换为 PPTX 时,Slide 对象用于保存对目标幻灯片的引用,而 IPPImage 类对象用于保存对图像集合中新添加的图像的引用。 add_image 方法有许多重载的构造函数,它们采用不同的参数,如字节、IPPImage 对象、Image 对象和内存流。
在本教程中,我们学习了将 PNG 文件转换为 Python 中的 PowerPoint。如果您想探索将 PDF 转换为演示文稿的过程,请参阅 如何使用 Python 将 PDF 转换为演示文稿 上的文章。