scanny / python-pptx

Create Open XML PowerPoint documents in Python
MIT License
2.35k stars 510 forks source link

Replacing the image in ppt by python #834

Open Yoonlala opened 2 years ago

Yoonlala commented 2 years ago

I'm trying to develop the program to replace the existing image with new image in existing ppt.

So I have found the code made by @kodonnell, @scanny .

This is it

import collections import collections.abc from PIL import Image from pptx import Presentation from pptx.util import Cm

PPT_TEMPLATE = 'TEST.pptx' REPLACEMENT_IMG = 'img.png'

presso = Presentation(PPT_TEMPLATE) slide = presso.slides[0] img = slide.shapes[0]

imgPic = img imgRID = imgPic.xpath('./p:blipFill/a:blip/@r:embed', namespaces=imgPic.nsmap)[0] imgPart = slide.related_parts[imgRID]

with open(REPLACEMENT_IMG, 'rb') as f: rImgBlob = f.read() rImgWidth, rImgHeight = Image.open(REPLACEMENT_IMG).size rImgWidth, rImgHeight = Cm(rImgWidth), Cm(rImgHeight)

imgPart._blob = rImgBlob

widthScale = float(rImgWidth) / img.width heightScale = float(rImgHeight) / img.height maxScale = max(widthScale, heightScale) scaledImgWidth, scaledImgHeight = int(rImgWidth / maxScale), int(rImgHeight / maxScale)

scaledImgLeft = int(img.left + (img.width - scaledImgWidth)/2) scaledImgTop = int(img.top + (img.height - scaledImgHeight)/2)

img.left, img.top, img.width, img.height = scaledImgLeft, scaledImgTop, scaledImgWidth, scaledImgHeight

**But I can't understand this code. emerging Error. So I couldn't revise some problem.

  1. imgPic = img
  2. imgRID = imgPic.xpath('./p:blipFill/a:blip/@r:embed', namespaces=imgPic.nsmap)[0]
  3. imgPart = slide.related_parts[imgRID]**

Please help me. thanks to everyone

kascodeo commented 1 year ago
import collections
import collections.abc

Above lines were used as workaround to avoid error in python-pptx regarding collections.abc. This issue is fixed in python-pptx-fix. In this package you dont have to use the lines to avoid these errors.