Search code examples
python-3.xpowerpointpython-pptx

How to add images to the slides using python?


I am doing process automation. it involve adding of images to the slides (total 8 images, 2 per slide, even some text below it.). I could add the image using pptx. but images need some cropping. How do I go about cropping it ? I also need to use some specific format for the slide. How to use that layout ? If someone can give process flow for doing it, would be grateful.


Solution

  • A picture shape in python-pptx has four crop properties (.crop_left, .crop_top, etc.). These each take a float value with e.g. 0.1 corresponding to 10%.

    but unfortunately these are read-only at present. If you need to crop your photos, you'll need to do it by hand or perhaps pre-process the images with something like the Python Imaging Library (PIL/Pillow) to modify their extents before inserting them.

    An image can be added to a slide in two ways. Either you can add it as a separate shape at an arbitrary location using slide.shapes.add_picture(), or you can add an image placeholder to the layout you use to create the slide and use placeholder.insert_picture(). This latter approach automatically draws the position and size from the placeholder, which helps keep those consistent across slides using that layout.