Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pil draw text with different colors

Hi to draw three different text with different options for ex:

  1. text-number-1 , font=arial, color=red
  2. text-number-2 , font=veranda, color=blue, size=30
  3. text-number-3 , font=tahoma, color=green, size=40 , align=center

text must go in new lines.

def pil_image(request):
text = request.GET.get('text', None)
font = str(request.GET.get('font', 'arial'))
fontsize = int(request.GET.get('fontsize', '20'))
textcolor = str(request.GET.get('textcolor', '000'))

import Image, ImageDraw, ImageFont, textwrap

img = Image.open('media/text/transparent.png')
img = img.convert("RGBA")
datas = img.getdata()
w, h = img.size

newData = []
for item in datas:
    if item[0] == 255 and item[1] == 255 and item[2] == 255:
        newData.append((255, 255, 255, 0))
    else:
        newData.append(item)

img.putdata(newData)

draw = ImageDraw.Draw(img)
font = ImageFont.truetype("media/text/fonts/" + font + ".ttf", fontsize, encoding="unic")


margin = offset = 40
for line in textwrap.wrap(text, width=48):
    w, h = draw.textsize(line)
    draw.text((margin, offset), line, font=font, fill='#'+textcolor)
    offset += font.getsize(line)[1]

del draw 

img.save("media/text/custom.png", "PNG")

return HttpResponse("<img src='/media/text/custom.png'>");
like image 206
Frankenstein Palinskij Avatar asked Feb 22 '13 14:02

Frankenstein Palinskij


People also ask

How do you change the color of text in an image in Python?

We simply use print() inside, but prepending the text with brightness and color codes, and appending Style. RESET_ALL in the end to reset to default color and brightness each time we use the function.

How to change text color in pillow?

Pillow allows you to change the color of your text by using the fill parameter. You can set this color using an RGB tuple, an integer or a supported color name.


2 Answers

The "fill" parameter should be a tuple with 4 number, as you use a RGBA colormode.

For opaque red:

draw.text((margin, offset), line, font=font, fill=(255,0,0,255) )
like image 102
MatthieuW Avatar answered Oct 04 '22 08:10

MatthieuW


Use hex value for colour, as follows:

draw.text((margin, offset), line, font=font, fill="#000")
like image 26
leenremm Avatar answered Oct 04 '22 09:10

leenremm