Lisa
Lisa

Reputation: 4416

python inserts pictures to powerpoint, how to set the width and height of the picture?

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')

Upvotes: 17

Views: 37008

Answers (2)

Jarad
Jarad

Reputation: 18913

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))

Upvotes: 22

scanny
scanny

Reputation: 28893

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.

Upvotes: 9

Related Questions