'Image aspect ratio using Reportlab in Python
I want to insert an image inside a frame. I found two ways to do this:
- drawImage(self, image, x, y, width=None, height=None, mask=None, preserveAspectRatio=False, anchor='c')
- Image(filename, width=None, height=None)
My question is: how can I add an image in a frame while preserving its aspect ratio?
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()
Solution 1:[1]
i had a similar problem and i think this works:
image = Image(absolute_path)
image._restrictSize(1 * inch, 2 * inch)
story.append(image)
I hope this helps!
Solution 2:[2]
I am super-late on this one, not sure when it was added but now the constructor for Image allows type='proportional' to be specified which will achieve the same desired output.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad |
| Solution 2 | cmcconomy |
