[英]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.