pil绘制不同颜色的文本 [英] pil draw text with different colors

查看:623
本文介绍了pil绘制不同颜色的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,您可以为ex绘制三个带有不同选项的文本:

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

文本必须换行.

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'>");

推荐答案

当您使用RGBA颜色模式时,"fill"参数应为具有4个数字的元组.

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

对于不透明的红色:

draw.text((margin, offset), line, font=font, fill=(255,0,0,255) )

这篇关于pil绘制不同颜色的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆