Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python pptx将图像与幻灯片中心对齐_Python_Python 2.7_Python Pptx - Fatal编程技术网

python pptx将图像与幻灯片中心对齐

python pptx将图像与幻灯片中心对齐,python,python-2.7,python-pptx,Python,Python 2.7,Python Pptx,我需要将图像添加到pptx幻灯片,并希望将其定位在幻灯片的中心,而无需手动计算大小和对齐方式 我发现了一个关于如何使用文本的问题: 以及有关使用文本执行此操作的文档: 但是找不到一种方法来制作图像 想法 它的工作方式与文本不同;图像上没有“中心对齐”或“对齐”属性。你需要使用一个公式 image.left = (prs.slide_width - image.width) / 2 回答2020年8月13日 这就是我的工作原理: from pptx import Presentation f

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

我发现了一个关于如何使用文本的问题:

以及有关使用文本执行此操作的文档:

但是找不到一种方法来制作图像


想法

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

image.left = (prs.slide_width - image.width) / 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)

我尝试使用幻灯片宽度,这是我获取AttributeError的错误:“幻灯片”对象没有属性“幻灯片宽度”@captainshai幻灯片宽度是演示文稿的属性(所有幻灯片都相同),而不是单个幻灯片的属性。因此,您需要使用
Presentation.slide\u width
属性
prs
以上是整个文档中使用的
Presentation
对象的“标准ish”变量名。对我来说,这给出了一个错误:
TypeError:value必须是整型,Get
。但是这很容易用
image.left=int((prs.slide\u width-image.width)/2)
解决,结果非常完美。谢谢你的原始答案(和问题)!使用此解决方案从
px\u to\u inches()
函数中获取
KeyError:'dpi'
。知道我做错了什么吗?这是粘贴箱: