11

New to python-pptx package. https://python-pptx.readthedocs.io/en/latest/ Would like to insert pictures to powerpoint. How can I set the width and height of the picture?

Code I have now:

from pptx import Presentation 
from pptx.util import Inches

img_path = 'monty-truth.png'

prs = Presentation() 
blank_slide_layout = prs.slide_layouts[6] 
slide = prs.slides.add_slide(blank_slide_layout)

left = top = Inches(1)
pic = slide.shapes.add_picture(img_path, left, top) 
prs.save('test.pptx')
Lisa
  • 4,126
  • 12
  • 42
  • 71

2 Answers2

15

Parameters of add_picture are:

add_picture(image_file, left, top, width=None, height=None)

To set the picture width and height, you just need to define the width and height parameters. In one of my projects, I got good picture height and placement with the following settings:

pic = slide.shapes.add_picture(img_path, pptx.util.Inches(0.5), pptx.util.Inches(1.75),
                               width=pptx.util.Inches(9), height=pptx.util.Inches(5))
Jarad
  • 17,409
  • 19
  • 95
  • 154
  • Hello. The method to set the width here is to provide the exact measurements to width and height. Any way we can employ the powerpoint UI way to increase the size to a certain percentage keeping the image proportions / aspect ratio intact? – Meet Jan 10 '22 at 13:04
  • Also, whenever we create a powerpoint using python-pptx, it creates it with 4:3 old style. Then even if we change the ratio to 16:9, it still doesn't change the measurements of all other objects in the layout file. They still stay in 4:3. Instead, if we go in PowerPoint and change the slide size manually to 16:9, all the layout files are also updated automatically. Can we do similar thing using python-pptx? – Meet Jan 10 '22 at 13:06
5

It looks like the details of that fell out of the documentation somehow Lisa, I'm glad you pointed it out.

The reason width and height don't appear in the example is because they are optional. If not supplied, the picture is inserted at it's "native" (full) size.

What might be more common is to provide only one of those two, and then python-pptx will do the math for you to make the unspecified dimension such as will preserve the aspect ratio. So if you have a big picture, say 4 x 5 inches, and want to shrink it down to 1 inch wide, you can call:

from pptx.util import Inches

pic = shapes.add_picture(image_path, left, top, Inches(1))

and the picture will come out sized to 1 x 1.25 (in this case) without you having to exactly know the dimensions of the original. Preserving the aspect ratio keeps the picture from looking "stretched", the way it would in this case if you made it 1 x 1 inches.

The same thing works with specifying the height only, if you know how tall you want it to appear and don't want to fuss with working out the proportional width.

If you specify both width and height, that's the size you'll get, even if it means the image is distorted in the process.

scanny
  • 26,423
  • 5
  • 54
  • 80