2010-09-14 77 views
0

我想通過使用PIL來繪製文本。但我的問題是我需要運行程序後再次裁剪文本圖像。我需要的只是文本,沒有邊界。任何人都可以建議? 謝謝。 這是我的代碼:通過PIL繪製無需裁剪的文本圖像

import Image, ImageDraw, ImageFont 
def draw (text, size, color) : 
    fontPath = '/home/FreeSansBold.ttf' 
    font = ImageFont.truetype(fontPath, size) 
    size2 = font.getsize(text) 
    im = Image.new('RGBA', size2, (0, 0, 0, 0)) 
    draw = ImageDraw.Draw(im) 
    draw.text((0, 0), text, font=font, fill=color) 
    im.save(text +'.png') 

drawA = draw('A', 200, 'green') 
drawC = draw('C', 200, 'blue') 
drawG = draw('G', 200, 'yellow') 
drawT = draw('T', 200, 'red') 
+0

我不明白你的問題,你能否澄清一下? – 2010-09-17 20:58:22

回答

1

你能說清楚你的意思是沒有邊界嗎?你想對文字邊緣進行緊縮嗎?如果是的話這應該工作:

import Image, ImageDraw, ImageFont 

def draw (text, size, color) : 
    fontPath = '/home/FreeSansBold.ttf' 
    font = ImageFont.truetype(fontPath, size) 
    size2 = font.getsize(text)  
    im = Image.new('RGBA', size2, (0, 0, 0, 0)) 
    draw = ImageDraw.Draw(im) 
    draw.text((0, 0), text, font=font, fill=color) 

    pixels = im.load() 
    width, height = im.size 
    max_x = max_y = 0 
    min_y = height 
    min_x = width 

    # find the corners that bound the letter by looking for 
    # non-transparent pixels 
    transparent = (0, 0, 0, 0) 
    for x in xrange(width): 
     for y in xrange(height): 
      p = pixels[x,y] 
      if p != transparent: 
       min_x = min(x, min_x) 
       min_y = min(y, min_y) 
       max_x = max(x, max_x) 
       max_y = max(y, max_y) 
    cropped = im.crop((min_x, min_y, max_x, max_y)) 
    cropped.save(text +'.png') 

drawA = draw('A', 200, 'green') 
drawC = draw('C', 200, 'blue') 
drawG = draw('G', 200, 'yellow') 
drawT = draw('T', 200, 'red') 

它產生這樣的圖像(我填寫在紅色的透明像素來顯示圖像更好的邊界:http://img43.imageshack.us/img43/3066/awithbg.png