[英]Draw text image without crop need by 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')
您能澄清無邊界的意思嗎? 您想讓文字緊貼圖像邊緣嗎? 如果是這樣,這應該起作用:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.