问题:
ppt里已有设置好大小位置的图片,替换成新的。
解决方案如下(来自pptx-replace这个包的源代码):
from pptx import Presentation
ppt = Presentation('店铺销量.pptx')
shops = ['李宁','森马']
for item,shop in enumerate(shops):
slide = ppt.slides[item]
img_name = f'./image/{shop}.jpg'
shape = slide.shapes[4]
new_shape = slide.shapes.add_picture(img_name,shape.left,shape.top,shape.width,shape.height)
new_pic = new_shape._element
old_pic = shape._element
old_pic.addnext(new_pic)
old_pic.getparent().remove(old_pic)
失败方案:网上搜到很多方案不靠谱,多张图片只能更新成一个图片:
方案一:https://www.reddit.com/r/learnpython/comments/11dyerr/replacing_images_in_powerpoint_with_pythong/
rom pptx import Presentation, parts
from pptx.enum.shapes import MSO_SHAPE_TYPE
prs = Presentation('test.pptx')
count = 1
for slide in prs.slides:
for shape in slide.shapes:
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
im = parts.image.Image.from_file(f'test{count}.png')
slide_part, rId = shape.part, shape._element.blip_rId
image_part = slide_part.related_part(rId)
image_part.blob = im._blob
count += 1
prs.save('new.pptx')
方案二:https://github.com/scanny/python-pptx/issues/116
ppt = Presentation(temp_name)
shops = ['李宁','森马']
for item,shop in enumerate(shops):
slide = ppt.slides[item]
img_name = f'/image/{shop}.jpg'
shape = slide.shapes[4]
imgPic = shape._pic
imgRID = imgPic.xpath('./p:blipFill/a:blip/@r:embed', namespace=imgPic.nsmap)[0]
imgPart = slide.part.related_part(imgRID)
with open(img_name, 'rb') as f:
rImgBlob = f.read()
imgPart._blob = rImgBlob