簡體   English   中英

使用PIL將文本繪制到圖像的中心

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

我有幾個叮咬我想畫到imagea。 問題是我希望每個字符串都顯示在每個圖像的中間。 我該怎么做? 或者如何知道字符串的長度(以字母為單位)? 謝謝

您可以在http://tools.jedutils.com/tools/center-text-image找到此實現

您可以使用該頁面在那里創建圖像,而不是自己實現例程,但代碼也包含在頁面中。

遵循妮可的建議

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字體有一個getize方法,你可以使用它來獲取字體的寬度和高度,你試過嗎? 例如

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