使用Python pptx获取图像文件名
我试图编写一个脚本,打开用户指定的ppt,读取它并查找图像文件名。我正在使用PythonPPTX包,因为这让我可以真正打开ppt文件。我试着浏览每一张幻灯片并检查该幻灯片中的图像,但我不知道如何使用pptx软件包来实现这一点,而且这个imo上的文档也不是很清楚 因此,在对文档进行进一步挖掘后,我发现这种方法可以起到作用:使用Python pptx获取图像文件名,python,python-pptx,Python,Python Pptx,我试图编写一个脚本,打开用户指定的ppt,读取它并查找图像文件名。我正在使用PythonPPTX包,因为这让我可以真正打开ppt文件。我试着浏览每一张幻灯片并检查该幻灯片中的图像,但我不知道如何使用pptx软件包来实现这一点,而且这个imo上的文档也不是很清楚 因此,在对文档进行进一步挖掘后,我发现这种方法可以起到作用: file = open(fileName, 'rb') ppt = Presentation(file) images = [] for slide in ppt.slide
file = open(fileName, 'rb')
ppt = Presentation(file)
images = []
for slide in ppt.slides:
for shape in slide.shapes:
print(shape.image)
if shape.image:
if isCorrectImageType(shape.image):
print(shape.image.filename)
file.close()
def isCorrectImageType(imageShape):
imgExtension = imageShape.content_type
filePattern = '(.jpg$|.jpeg$|.png$|.gif$)'
image = re.search(filePattern, imgExtension)
print(image.group(0))
return image.group(0)
这可以工作,但是它不会返回正确的文件名。它返回image.png,而文件名为myfile.png如果图像是从文件插入的,则图像文件名仅存储在XML中。如果图像是从二进制流导入的(由
python-pptx
之类的程序导入),则没有可用的文件名,因此将使用图像。{ext}
格式。使用PowerPoint将图像粘贴到位时也是如此
因此,文件名不一定总是可用的
但是,记录后,可在图片形状的descr
属性中使用:
from pptx.enum.shapes import MSO_SHAPE_TYPE
for shape in slide.shapes:
if shape.shape_type != MSO_SHAPE_TYPE.PICTURE:
continue
picture = shape
print(picture._pic.nvPicPr.cNvPr.get('descr'))
此代码访问如下所示的XML:
<p:pic>
<p:nvPicPr>
<p:cNvPr id="6" name="Picture 5" descr="python-logo.gif"/>
<p:cNvPicPr/>
<p:nvPr/>
</p:nvPicPr>
...
...
并且应该返回值'python-logo.gif'