I need to add an image to a pptx slide, and want to locate it in the center of the slide, without having to calculate the size and alignment manually,
I found a question about doing so with text: question about center aligning text
And the documentation about doing so with text: documentation about center aligning text
But can't find a way to do it for an image,
Ideas?
It's not going to work the same way as text; there's no center justification or alignment property on an image. You'll need to use a formula.
image.left = (prs.slide_width - image.width) / 2
Answer 08/13/2020
This is what worked for me:
from pptx import Presentation
from pptx.util import Inches
from PIL import Image
# instantiate presentation
prs = Presentation()
# change slide sizes to Widescreen
slide_size = (16, 9)
prs.slide_width, prs.slide_height = Inches(slide_size[0]), Inches(slide_size[1])
# convert pixels to inches
def px_to_inches(path):
im = Image.open(path)
width = im.width / im.info['dpi'][0]
height = im.height / im.info['dpi'][1]
return (width, height)
img = px_to_inches('logo.png')
# insert logo image
left = Inches(slide_size[0] - img[0]) / 2
top = Inches(slide_size[1] - img[1]) / 2
pic = slide.shapes.add_picture('logo.png', left, top)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With