我正在尝试使一些文本重叠在图像上,这是我的以下代码。
from PIL import Image, ImageDraw, ImageFont
msg = "This is a test phrase, so please shrink the text."
im = Image.open("test.jpg")
draw = ImageDraw.Draw(im)
W, H = im.size
myFont =
ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf")
w, h = draw.textsize(msg, font=myFont)
draw.text(((W-w)/2,(H-h)/2), msg, fill="black", font=myFont)
im.save("sample-out.png", "PNG")
我需要的是在中间缩放的文本,但要介于像素宽度和高度1600,300之间。谁先取得成就。
我想这与字体大小的增加有关,但我无法弄清楚。
答案 0 :(得分:3)
您可以使用ImageFont.truetype()函数的第二个参数来增加字体大小。
myFont = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", 32)
答案 1 :(得分:0)
因此很幸运,这是下面的代码。请注意,某些变量更改了上面原始代码的名称,但这可行。
from PIL import ImageFont, ImageDraw, Image
image = Image.open('test.jpg')
draw = ImageDraw.Draw(image)
txt = "share/fonts/truetype/customfonts/KeepC"
fontsize = 1 # starting font size
W, H = image.size
# portion of image width you want text width to be
blank = Image.new('RGB',(1000, 300))
font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)
print image.size
print blank.size
while (font.getsize(txt)[0] < blank.size[0]) and (font.getsize(txt)[1] < blank.size[1]):
# iterate until the text size is just larger than the criteria
fontsize += 1
font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)
# optionally de-increment to be sure it is less than criteria
fontsize -= 1
font = ImageFont.truetype("/usr/share/fonts/truetype/customfonts/KeepCalm-Medium.ttf", fontsize)
w, h = draw.textsize(txt, font=font)
print 'final font size',fontsize
draw.text(((W-w)/2,(H-h)/2), txt, font=font, fill="black") # put the text on the image
image.save('sample-out.png') # save it