Skip to main content
Practice

Inserting and Adjusting Images on a Slide

When you need to add multiple images to slides repeatedly or adjust the images' positions, doing this manually one-by-one can be very cumbersome.

By using the 'python-pptx' library, you can insert images into slides in a programmatic way and adjust the images' size and position using a script.

In this lesson, we will learn how to insert images into slides and how to adjust their positions and sizes as desired.


Adding an Image to a Slide

In 'python-pptx', the add_picture() method is used to insert images.

The add_picture method takes the image path and the position where the image will be inserted (distance from the left, distance from the top) as arguments.

Inserting an Image
# Image file path
img_path = 'path/to/your/image.png'

# Position adjustment: 2 inches from the left, 1 inch from the top
left = Inches(2)
top = Inches(1)

# Insert image: image path, left position, top position
slide.shapes.add_picture(img_path, left, top)

In slide.shapes.add_picture(img_path, left, top), img_path specifies the path to the image file to be inserted (e.g., 'C:/Users/username/image.png').

left specifies how far the image is from the left edge, and top specifies how far the image is from the top edge.


Placing Images with Desired Dimensions

If you do not specify the size of the image, it will be inserted in its original size.

To adjust the size of the image being inserted, you can additionally specify the width and height values.

Adjusting Image Size and Position
# Image file path
img_path = 'path/to/your/image.png'

# Position adjustment: 2 inches from the left, 1 inch from the top
left = Inches(2)
top = Inches(1)

# Image size adjustment: 3 inches wide, 3 inches tall
width = Inches(3) # Set the width of the image
height = Inches(3) # Set the height of the image

# Insert image: image path, left position, top position, width, height
slide.shapes.add_picture(img_path, left, top, width, height)

By adding width and height like in slide.shapes.add_picture(img_path, left, top, width, height), you can adjust the size of the image.

The fourth parameter of the add_picture method represents the width of the image, and the fifth parameter represents the height of the image.


Note: Maintaining Aspect Ratio

If you want to adjust the size of the image while maintaining its original aspect ratio, you can specify either the width or height only, and the other value will be adjusted automatically.

Adjusting Image Size While Maintaining Aspect Ratio
# Specify only the width, and the height will be adjusted automatically
slide.shapes.add_picture(img_path, left, top, width=Inches(4))

In this example, the width of the image is set to 4 inches, and the height will be automatically adjusted to maintain the original aspect ratio of the image.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.