gpt4 book ai didi

Python-pptx : issue with insert_picture() function - 'sha1' AttributeError

转载 作者:太空宇宙 更新时间:2023-11-03 13:59:27 26 4
gpt4 key购买 nike

我正在尝试编写一个基本脚本来更新 PowerPoint (2016) 演示文稿 template.pptx,其中包含图像的预定义占位符。我遇到了 insert_picture() 函数的问题。

例如,template.pptx 的第四张幻灯片包含图片占位符:

from pptx import Presentation

prs = Presentation('template.pptx')

slide4 = prs.slides[3]

for shape in slide4.placeholders:
print('%d %s' % (shape.placeholder_format.idx, shape.name))

给出以下输出

>>> 
0 Title 3
10 Picture Placeholder 7

我继续

placeholder = slide4.placeholders[10] # idx key, not position
picture = placeholder.insert_picture('test.jpg')

这会引发以下错误:

File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 323, in insert_picture
pic = self._new_placeholder_pic(image_file)
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 334, in _new_placeholder_pic
rId, desc, image_size = self._get_or_add_image(image_file)
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 345, in _get_or_add_image
image_part, rId = self.part.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\parts\slide.py", line 42, in get_or_add_image_part
image_part = self._package.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\package.py", line 50, in get_or_add_image_part
return self._image_parts.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\package.py", line 159, in get_or_add_image_part
image_part = self._find_by_sha1(image.sha1)
File "C:\Python273\lib\site-packages\pptx\package.py", line 171, in _find_by_sha1
if image_part.sha1 == sha1:
AttributeError: 'Part' object has no attribute 'sha1'

我在这些论坛中看到过这个“sha1”错误,但并不完全理解它(我是个新手)。

有趣的是(令人沮丧),我在从头开始创建 PowerPoint 时没有遇到这个问题(按照 python-pptx 0.6.7 文档中的示例):

prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1] # idx key, not position
picture = placeholder.insert_picture('test.jpg')
prs.save('new.pptx')

这运行得很好,因此我很困惑。任何帮助将非常感激。谢谢!

(Windows 7、Python 2.7.3)

最佳答案

我已经找到了这个问题的可能原因!对我来说,问题是演示文稿中包含的图像不是 jpg、png 或 gif 格式的。这是一个 tif 文件。对于这些文件,没有 sha1,因此脚本会引发异常。转换/删除这些文件使问题消失!

请告诉我这是否也适合您。

关于Python-pptx : issue with insert_picture() function - 'sha1' AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49357270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com