簡體   English   中英

使用python pil擴展圖像並在擴展區域上添加文本

[英]Extending a image and adding text on the extended area using python pil

我正在為每張票創建QRcode。 QRcode為圖像格式。 在此處輸入圖片說明

我想在兩側(即頂部和底部)垂直擴展此圖像。 在擴展區域中,我想添加一些其他數據,例如:

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

圖像以這種方式旋轉:

在此處輸入圖片說明

如您所見,文本將添加到圖像中,而不會擴展圖像本身。 另外,由於文本不會擴展圖像, text_showtime不會插入其他數據,例如text_movietext_showtimetext_date

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

首先創建一個較大的圖像以在其上寫入文本,然后將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。 我沒有麻煩定義一個非默認字體。

這是結果。

結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM