在Python中使用Reportlab的图像纵横比
我想在框架内插入一个图像。我找到了两种方法:在Python中使用Reportlab的图像纵横比,python,image,pdf,reportlab,Python,Image,Pdf,Reportlab,我想在框架内插入一个图像。我找到了两种方法: drawImage(self、image、x、y、width=None、height=None、mask=None、preserveAspectRatio=False、anchor='c') 图像(文件名,宽度=无,高度=无) 我的问题是:如何在保持图像纵横比的同时在帧中添加图像 from reportlab.lib.units import cm from reportlab.pdfgen.canvas import Canvas from rep
from reportlab.lib.units import cm
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Frame, Image
c = Canvas('mydoc.pdf')
frame = Frame(1*cm, 1*cm, 19*cm, 10*cm, showBoundary=1)
"""
If I have a rectangular image, I will get a square image (aspect ration
will change to 8x8 cm). The advantage here is that I use coordinates relative
to the frame.
"""
story = []
story.append(Image('myimage.png', width=8*cm, height=8*cm))
frame.addFromList(story, c)
"""
Aspect ration is preserved, but I can't use the frame's coordinates anymore.
"""
c.drawImage('myimage.png', 1*cm, 1*cm, width=8*cm, preserveAspectRatio=True)
c.save()
您可以使用原始图像的大小来计算其纵横比,然后使用它来缩放目标宽度、高度。您可以将其封装在函数中以使其可重用:
from reportlab.lib import utils
def get_image(path, width=1*cm):
img = utils.ImageReader(path)
iw, ih = img.getSize()
aspect = ih / float(iw)
return Image(path, width=width, height=(width * aspect))
story = []
story.append(get_image('stack.png', width=4*cm))
story.append(get_image('stack.png', width=8*cm))
frame.addFromList(story, c)
使用248 x 70像素stack.png的示例:
我也有类似的问题,我认为这是可行的:
image = Image(absolute_path)
image._restrictSize(1 * inch, 2 * inch)
story.append(image)
我希望这有帮助 谢谢你的解决方案。我希望有人能将此添加到API中。这是这个问题的最佳答案。我们应该将类似的问题合并到这个问题中。太好了!我刚刚添加了
**kwargs
,以维护您想要通过的任何额外功能。它看起来是这样的:def get_image(路径,宽度=1*cm,**kwargs)
和返回图像(路径,宽度=宽度,高度=(宽度*纵横比),**kwargs)
。现在我可以做get_image('stack.png',width=8*cm,hAligh='CENTER')