[英]Draw text image without crop need by PIL
I would like to draw a text by using PIL. 我想使用PIL绘制文本。 But my problem is I need to crop the text image again after run the program.
但是我的问题是我需要在运行程序后再次裁剪文本图像。 The thing i need is only text, no border.
我需要的只是文本,没有边框。 Any one can suggest?
有人可以建议吗? Thank you.
谢谢。 This is my code:
这是我的代码:
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')
Could you clarify what you mean by no border? 您能澄清无边界的意思吗? Are you wanting text tight against edge of the image?
您想让文字紧贴图像边缘吗? If so this should work:
如果是这样,这应该起作用:
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')
It produces an image like this (I filled in the transparent pixels with red to show the bounds of the image better: http://img43.imageshack.us/img43/3066/awithbg.png 它产生这样的图像(我用红色填充透明像素以更好地显示图像的边界: http : //img43.imageshack.us/img43/3066/awithbg.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.