2011-03-16 17 views
8

Desidero inserire un'immagine all'interno di una cornice. Ho trovato due modi per farlo:Proporzioni immagine utilizzando Reportlab in Python

  1. drawImage (self, immagine, x, y, width = None, altezza = Nessuno, maschera = Nessuno, preserveAspectRatio = False, anchor = 'c')
  2. Immagine (nome del file, width = None, height = None)

la mia domanda è: come posso aggiungere un'immagine in una cornice, preservando le proporzioni?

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

risposta

27

È possibile utilizzare dimensioni dell'immagine originale per calcolare il suo rapporto di aspetto, quindi utilizzare tale per scalare la larghezza di destinazione, altezza. Si può avvolgere questo in una funzione per renderlo riutilizzabile:

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) 

Esempio utilizzando uno stack.png 248 x 70 pixel:

enter image description here

+0

Grazie per questa soluzione. Spero che qualcuno aggiungerà questo all'API. – citn

+0

Questa è la migliore risposta a questa domanda. Ci sono domande simili che dovremmo fondere in questo. – jimh

8

Ho avuto un problema simile e credo che questo funziona :

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

Spero che questo aiuti!

Problemi correlati