2011-03-16 5 views
8

프레임 안에 이미지를 삽입하고 싶습니다. 나는이 두 가지 방법을 발견 :Python에서 Reportlab을 사용하는 이미지 종횡비

  1. 의 drawImage (자기, 이미지, X, Y, 폭 = 없음을 높이 = 없음, 마스크 = 없음, preserveAspectRatio = 거짓, 앵커 = 'C')
  2. 이미지 (파일 이름, 너비 = 없음, 높이 = 없음)

질문 : 어떻게 가로 세로 비율을 유지하면서 이미지를 추가 할 수 있습니까?

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

답변

27

원본 이미지의 크기를 사용하여 가로 세로 비율을 계산 한 다음이를 사용하여 대상 너비와 높이를 조정할 수 있습니다. 248 X 70 픽셀 stack.png 사용

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) 

예 : 당신은 다시 사용할 수 있도록하는 기능이를 마무리 할 수 ​​enter image description here

+0

이 해결 방법을 이용해 주셔서 감사합니다. 누군가가 이것을 API에 추가하기를 바랍니다. – citn

+0

이것은이 질문에 대한 최선의 대답입니다. 우리가 이와 비슷한 질문을 병합해야합니다. – jimh

8

내가 비슷한 문제가 있었다을 그리고 난이 작품을 생각한다 :

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

이 정보가 도움이되기를 바랍니다.

관련 문제