2017-08-25 47 views
16

我正在嘗試動態增加圖像的大小,以提供給draw.text()的字體和文本。PIL如何縮放與圖像上繪製的文字相關的圖像

Orignal問題是基於名稱和字體用戶選擇創建簽名圖像。

這裏是我的代碼

from PIL import (Image, ImageDraw, ImageFont,) 

width=20 
height=20 
selected_font='simply_glomrous.ttf' 
font_size=30 

img = Image.new('RGBA', (width, height), (255, 255, 255, 0)) 
draw = ImageDraw.Draw(img) 
font = ImageFont.truetype(selected_font, font_size) 
draw.text((0,0), "Adil Malik", (0,0,0), font) 
img.save('signature.png') 

但我仍然有在寬度和高度定義相同的圖像尺寸。我們可以根據字體和大小動態調整圖像大小嗎?

注意:這個問題是相反this stackoverflow question

回答

10

不幸的是,沒有人能夠回答我的問題。

基本上,在設置字體大小的時候,您不能設置固定寬度和高度。兩者都相互依賴。所以如果增加,第二個也增加。

於是我想出了另一種解決方案。我只是設置字體大小,然後基於該字體大小,我設置的寬度和高度。

from PIL import (Image, ImageDraw, ImageFont,) 

name = 'Adil Malik' 
selected_font='simply_glomrous.ttf' 
font_size=30 

font = ImageFont.truetype(selected_font, font_size) 
font_size = font.getsize(name) 

img = Image.new('RGBA', (font_size[0], font_size[0]), (255, 255, 255, 0)) 
draw = ImageDraw.Draw(img) 
font = ImageFont.truetype(selected_font, font_size) 
draw.text((0,0), name, (0,0,0), font) 
img.save('signature.png') 
1

首先,你需要得到你的秤正確:您是從給定的點的字體大小,其定義爲1/72英寸開始;那些是「現實世界」的尺度。您正在繪製的圖像以像素定義。僅當您定義每英寸像素比率時,像素纔會與英寸/點關聯。

所以你思考問題的方式是一種落後的:你需要開始與像素您有(從源或目標圖像),然後計算合適的字體大小。如果您希望用戶選擇字體大小,則需要定義(或要求)目標DPI值,以便在涉及的比例單位之間進行更改。

+0

但是,我的問題仍然存在。我不知道文本的長度是多少。所以我不能從固定圖像大小開始。 –

2

你正在尋找的功能是Draw.textsize方法這需要一個文本字符串和繪圖選項作爲輸入並返回呈現的文本的寬度和高度。

http://effbot.org/imagingbook/imagedraw.htm#tag-ImageDraw.Draw.textsize

您可以使用Draw類與具有零寬度和高度的圖像,然後調用該方法來確定文本的您正在尋找呈現的尺寸。一旦你知道了這些尺寸,你就可以相應地調整圖像的大小。例如:

from PIL import ImageDraw, ImageFont, Image 

# parameters 
text = "My Name" 
selected_font = "simply_glomrous.ttf" 
font_size = 30 

# get the size of the text 
img = Image.new('RGBA', (0,0), (255, 255, 255, 0)) 
font = ImageFont.truetype(selected_font, font_size) 
draw = ImageDraw.Draw(img) 
text_size = draw.textsize(text, font) 

# resize and draw 
img = img.resize(text_size) 
draw.text((0,0), text, (0,0,0), font) 
img.save('signature.png') 
3

如果你可以使用OpenCV的和numpy的,你可以

  1. 檢查使用getTextSize
  2. 創建使用numpy.ones白色圖像((文字大小高度,寬度,3) np.uint8)*

  3. 保存圖像使用imwrite 255

  4. 添加文本使用putText圖像。

查看herehere供參考。