Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pptx align image to center of slide

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?

like image 761
thebeancounter Avatar asked Oct 20 '16 09:10

thebeancounter


2 Answers

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
like image 28
scanny Avatar answered Oct 23 '22 22:10

scanny


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)
like image 130
igorkf Avatar answered Oct 23 '22 20:10

igorkf