我想使用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 :(得分: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