Luk*_*pel 8 python python-imaging-library
我正在尝试使一些文本重叠在图像上,这是我的以下代码。
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")
Run Code Online (Sandbox Code Playgroud)
我需要的是文本要在中间缩放,但要介于像素宽度和高度1600,300之间。谁先取得成就。
我想这与字体大小的增加有关,但我不知道。
所以通过一点运气想通了,这是下面的代码。请注意,某些变量从上面的原始代码更改了名称,但这是有效的。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
587 次 |
| 最近记录: |