简体   繁体   English

使用PIL将文本绘制到图像的中心

[英]draw text to center of the image using PIL

I have a few stings I would like to draw to imagea. 我有几个叮咬我想画到imagea。 the thing is that I want each string to be displayed in the middle of each image. 问题是我希望每个字符串都显示在每个图像的中间。 how do I do it? 我该怎么做? or how can I know the length in pixels of a string (giving ofcourse the font)? 或者如何知道字符串的长度(以字母为单位)? thanks 谢谢

You could find an implementation of this at http://tools.jedutils.com/tools/center-text-image 您可以在http://tools.jedutils.com/tools/center-text-image找到此实现

You could use that page for creating the image right there instead of implementing the routine yourself but the code is included on the page too. 您可以使用该页面在那里创建图像,而不是自己实现例程,但代码也包含在页面中。

Following Nicole's advise 遵循妮可的建议

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 )

` `

PIL font's do have a getsize method which you can use to get width and height of font, did you try that? PIL字体有一个getize方法,你可以使用它来获取字体的宽度和高度,你试过吗? eg 例如

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM