[英]Image aspect ratio using Reportlab in Python
我想在框架内插入图像。 我找到了两种方法来做到这一点:
我的问题是:如何在保持纵横比不变的情况下在框架中添加图像?
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)
我希望这有帮助!
我在这方面超晚了,不确定它是什么时候添加的,但现在 Image 的构造函数允许指定type='proportional'
,这将实现相同的期望 output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.