使用PIL在图像中心绘制文本
我有几段文字想要放到图片上。问题是我希望每段文字都能显示在每张图片的中间。我该怎么做呢?或者我怎么才能知道一段文字的像素长度(当然是要知道字体的情况下)?谢谢!
2 个回答
2
你可以在这个网址找到相关的实现:http://tools.jedutils.com/tools/center-text-image
你可以直接在那个页面上创建图像,而不需要自己去写代码,不过页面上也有代码可以参考。
根据Nicole的建议
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import StringIO
filter_dict = {
'BLUR' : ImageFilter.BLUR,
'CONTOUR' : ImageFilter.CONTOUR,
'DETAIL' : ImageFilter.DETAIL,
'EDGE_ENHANCE' : ImageFilter.EDGE_ENHANCE,
'EDGE_ENHANCE_MORE' : ImageFilter.EDGE_ENHANCE_MORE,
'EMBOSS' : ImageFilter.EMBOSS,
'FIND_EDGES' : ImageFilter.FIND_EDGES,
'SMOOTH' : ImageFilter.SMOOTH,
'SMOOTH_MORE' : ImageFilter.SMOOTH_MORE,
'SHARPEN' : ImageFilter.SHARPEN
}
def get_font_full_path(font_path,font_name):
ext = '.TTF' if font_name.upper() == font_name else ".ttf"
return font_path + font_name + ext
def create_image(font_name, font_size, font_color, width, height, back_ground_color, text, img_type="JPEG", image_filter=None):
font_full_path = get_font_full_path(font_path,font_name)
font = ImageFont.truetype ( font_full_path, font_size )
im = Image.new ( "RGB", (width,height), back_ground_color )
draw = ImageDraw.Draw ( im )
text_x, text_y = font.getsize(text)
x = (width - text_x)/2
y = (height - text_y)/2
draw.text ( (x,y), text, font=font, fill=font_color )
if image_filter:
real_filter = filter_dict[image_filter]
im = im.filter(real_filter)
im.save ( "sample.jpg", format=img_type )
`
2
PIL字体确实有一个叫做getsize的方法,你可以用它来获取字体的宽度和高度,你试过这个吗?
from PIL import Image, ImageDraw, ImageFont
fontFile = "/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"
font = ImageFont.truetype(fontFile, 10)
text="anurag"
print font.getsize(text)
assert font.getsize(text)[0]*2 == font.getsize(text*2)[0]