简体   繁体   中英

Draw text image without crop need by PIL

I would like to draw a text by using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM