在Python中使用Reportlab处理图像纵横比

18 投票
3 回答
27693 浏览
提问于 2025-04-16 13:49

我想在一个框架里插入一张图片。我找到了两种方法来做到这一点:

  1. 使用drawImage(self, image, x, y, width=None, height=None, mask=None, preserveAspectRatio=False, anchor='c')
  2. 使用Image(filename, width=None, height=None)

我的问题是:我怎么才能在框架里添加一张图片,同时保持它的宽高比呢?

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()

3 个回答

2

我来得有点晚,不太确定这个功能是什么时候加上的,但现在Image的构造函数可以指定type='proportional',这样就能得到想要的效果了。

14

我遇到过类似的问题,我觉得这个方法有效:

   image = Image(absolute_path)
   image._restrictSize(1 * inch, 2 * inch)
   story.append(image)

希望这对你有帮助!

53

你可以用原始图片的大小来计算它的宽高比,然后用这个比例来调整你想要的宽度和高度。你可以把这个过程写成一个函数,这样以后就可以重复使用了:

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的例子:

enter image description here

撰写回答