【问题标题】:python pptx align image to center of slidepython pptx将图像对齐到幻灯片的中心
【发布时间】:2016-10-20 09:05:01
【问题描述】:

我需要在pptx幻灯片中添加图片,并且想将其定位在幻灯片的中心,而无需手动计算大小和对齐方式,

我发现了一个关于使用文本执行此操作的问题: question about center aligning text

以及有关使用文本执行此操作的文档: documentation about center aligning text

但是找不到图片的方法,

想法?

【问题讨论】:

    标签: python python-2.7 python-pptx


    【解决方案1】:

    它的工作方式与文本不同;图像上没有中心对齐或对齐属性。您需要使用公式。

    image.left = (prs.slide_width - image.width) / 2
    

    【讨论】:

    • 我尝试使用幻灯片宽度,这是我得到的错误 AttributeError: 'Slide' object has no attribute 'slide_width'
    • @captainshai 幻灯片宽度是演示文稿的属性(所有幻灯片都相同),而不是单个幻灯片。所以你需要使用Presentation.slide_width 属性。上面的prsPresentation 对象的“标准”变量名称,在整个文档中都使用。
    • 对我来说,这给出了一个错误:TypeError: value must be an integral type, got <class 'float'>。但这很容易用image.left = int((prs.slide_width - image.width) / 2) 解决,结果很完美。感谢您的原始答案(和问题)!
    【解决方案2】:

    回答 2020 年 8 月 13 日

    这对我有用:

    from pptx import Presentation
    from pptx.util import Inches
    from PIL import Image
    
    
    # instantiate presentation
    prs = Presentation()
    
    # change slide sizes to Widescreen
    slide_size = (16, 9)
    prs.slide_width, prs.slide_height = Inches(slide_size[0]), Inches(slide_size[1])
    
    # convert pixels to inches
    def px_to_inches(path):
        
        im = Image.open(path)
        width = im.width / im.info['dpi'][0]
        height = im.height / im.info['dpi'][1]
        
        return (width, height)
    
    img = px_to_inches('logo.png')
    
    # insert logo image
    left = Inches(slide_size[0] - img[0]) / 2
    top = Inches(slide_size[1] - img[1]) / 2
    pic = slide.shapes.add_picture('logo.png', left, top)
    

    【讨论】:

    • 使用此解决方案从px_to_inches() 函数中获取KeyError: 'dpi'。知道我做错了什么吗?这是 PasteBin:pastebin.com/71y0qD8Z
    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多