13

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?

Community
  • 1
  • 1
thebeancounter
  • 4,261
  • 8
  • 61
  • 109

2 Answers2

14

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
scanny
  • 26,423
  • 5
  • 54
  • 80
  • i tried using the slide width, and this is the error i am getting AttributeError: 'Slide' object has no attribute 'slide_width' – thebeancounter Oct 27 '16 at 11:20
  • 1
    @captainshai The slide width is a property of the presentation (same for all slides), not for an individual slide. So you need to use the `Presentation.slide_width` property. `prs` above is the "standard-ish" variable name for a `Presentation` object, used throughout the documentation. – scanny Oct 27 '16 at 19:56
  • 2
    For me, this gave an error: `TypeError: value must be an integral type, got `. But that was easy to fix with `image.left = int((prs.slide_width - image.width) / 2)` and the result is perfect. Thanks for the original answer (and question)! – marcu1000s Oct 16 '19 at 14:45
3

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)
igorkf
  • 3,159
  • 2
  • 22
  • 31
  • 1
    Getting a `KeyError: 'dpi'` from within the `px_to_inches()` function with this solution. Any idea what I'm doing wrong? Here's the PasteBin: https://pastebin.com/71y0qD8Z – Mikitz06 Nov 22 '20 at 19:36