2017-04-08 64 views
1

我正在爲每張票創建QR碼。 QRcode是圖像格式。 enter image description here使用python pil擴展圖像並在擴展區域添加文本

我想在兩側(即頂部和底部)垂直延伸此圖像。而在擴展區域我想添加一些像這樣的額外數據:

Theater Name 
_____________________ 
|     | 
|     | 
| QR CODE   | 
|     | 
|     | 
|     | 
|     | 
|     | 
|___________________| 

Seat id: 24 C 
Movie: The baby boss 
Showtime: 2:30 pm 
Date: 09/04/17 

現在我這樣做的方法來添加圖像:

image = Image.open('qrcode.jpg') 
width, height = image.size 
draw = ImageDraw.Draw(image) 
text_cinema = "RPG Cinema" 
text_seat = "Seat: 15C Balcony" 
text_movie = "The baby boss" 
text_showtime = "02:30 pm" 
text_date = "09/04/17" 
font = ImageFont.truetype('font.ttf', 24) 
draw.text((40, 5), text_cinema, font=font) 
draw.text((40,height - 40), text_seat, font=font) 
draw.text((40,height + 40), text_movie, font=font) 
draw.text((40,height + 40), text_showtime, font=font) 
image.save(str(time()).replace('.', '_') + '.jpg') 

和圖像變成了這樣:

enter image description here

正如您所看到的,文本被添加到圖像中,而不是擴展圖像本身。此外,其他數據(如text_movie,text_showtimetext_date)未被插入,因爲文本不會擴展圖像。

如何擴展圖像並將文本插入擴展圖像區域?

+0

下面是擴大圖像的建議:https://stackoverflow.com/questions/1572691/in-python-python-image-library-1-1-6-how-can-i- expand-the-canvas-without-resiz(我之前的評論與錯誤的問題有關)。 – Craig

回答

1

首先創建一個更大的圖像,在其上寫入文本,然後將QR粘貼到該圖像作爲背景。

>>> from PIL import Image 
>>> background = Image.new('RGBA', (176, 225), (255,255,255,255)) 
>>> from PIL import ImageDraw 
>>> draw = ImageDraw.Draw(background) 
>>> draw.text((5,5), "Top text", (0,0,0)) 
>>> draw.text((5,210),"Bottom", (0,0,0)) 
>>> qr = Image.open('qr.png') 
>>> background.paste(qr, (0,20)) 
>>> background.save('back.png') 

在這種情況下QR是176x176。生成的圖像是176x225。我沒有費力去定義一個非默認的字體。

結果如下。

result