0

I am working on a project and I would like to extract the dimension of each image that I have on the slide. I saw that python-pptx can do this, but I'm not getting it. Can anyone help?

I tried this, but it only returns the slide images:

from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE

n=0
def write_image(shape):
    global n
    image = shape.image
    # ---get image "file" contents---
    image_bytes = image.blob
    # ---make up a name for the file, e.g. 'image.jpg'---
    image_filename = 'image{:03d}.{}'.format(n, image.ext)
    n += 1
    print(image_filename)
    with open(image_filename, 'wb') as f:
        f.write(image_bytes)

def visitor(shape):
    if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
        for s in shape.shapes:
            visitor(s)
    if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
        write_image(shape)

def iter_picture_shapes(prs):
    for slide in prs.slides:
        for shape in slide.shapes:
            visitor(shape)
iter_picture_shapes(Presentation('/content/drive/MyDrive/Slides/Apresentação Artigo.pptx'))
Belhadjer Samir
  • 1,461
  • 7
  • 15
Andre
  • 11
  • 3
  • You need to show what you've tried. –  Feb 01 '21 at 19:46
  • Are you looking for the size of the image "as displayed" on the slide (like 5 cm x 3 cm)? Or are you looking for the _pixel_ dimensions of the underlying image (like 740 px X 365 px), like before any scaling that may have been done to make it fit on the slide? – scanny Feb 01 '21 at 20:53
  • I am looking for the image size as it is displayed on the slide – Andre Feb 01 '21 at 21:35
  • @scanny I am looking for the image size as it is displayed on the slide – Andre Feb 01 '21 at 22:03

2 Answers2

0

you can use placeholder.insert_picture to insert image then get the picture dimension of the image which is the same position and size as the placeholder example :

picture = placeholder.insert_picture(...)
width, height = picture.image.size  # ---width and height are int pixel-counts

check this answer

Belhadjer Samir
  • 1,461
  • 7
  • 15
0

A Picture is a shape, and like all shapes, it has a position and size.

print("width is %s cm" % picture.width.cm)
print("height is %s cm" % picture.height.cm)

The value returned by Picture.width (or .height) is an Emu object. Emu stands for English-Metric Unit, of which there are 914400 per inch. It is an integer measure designed to be evenly divisible by millimeters, inches, fractions of inches down to 32nds, points, picas, and generally all the different measures you might find in publishing.

The Emu object has a number of convenience properties like .cm, .mm, .inches, etc. that allow you to get the value converted into your measure of choice. This section in the documentation has more on that subject: https://python-pptx.readthedocs.io/en/latest/user/autoshapes.html?highlight=english#understanding-english-metric-units

scanny
  • 26,423
  • 5
  • 54
  • 80