Phoenix
Phoenix

Reputation: 83

PIL draw text without gray outline

I'm trying to generate text using PIL for a black and white image only, but the text has this gray outline that I'm trying to get rid off.

image = np.zeros((600, 600), dtype=np.uint8)
image[:] = 255
img = Image.fromarray(image, 'L')
fnt = ImageFont.truetype('Arial.ttf', 50)
draw = ImageDraw.Draw(img)
draw.text((50,100), 'test , test', font=fnt)

enter image description here

What do I need to do to get the text to appear only in black? No gray area around it?

Upvotes: 1

Views: 1072

Answers (1)

Alistair Carscadden
Alistair Carscadden

Reputation: 1228

Using the ImageFont.getmask and ImageFont.getsize methods I was able to create a PIL.Image object that masks text with hard edges.

enter image description here

from PIL import Image, ImageFont

fnt = ImageFont.truetype('arial.ttf', 50)
text = 'test, test'
img = Image.new('1', fnt.getsize(text))
mask = [x for x in fnt.getmask(text, mode='1')]
img.putdata(mask)

This PIL.Image object (img) can be used to add the text to your image wherever you please, if you need more info on this I can build an example for you. Keep in mind that img.mode is '1', which means black and white. Every pixel (returned by img.getpixel) is either 0 or 255.

Upvotes: 2

Related Questions