用不同颜色绘制文本

2024-09-23 04:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,为ex绘制三个不同的文本和不同的选项:

  1. text-number-1,字体=宋体,颜色=红色
  2. 文本编号2,字体=阳台,颜色=蓝色,大小=30
  3. text-number-3,font=宋体,color=绿色,size=40,align=居中

文本必须换行。

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

Tags: text文本imggetpngrequestlineitem
2条回答

在使用RGBA colormode时,“fill”参数应该是一个有4个数字的元组。

对于不透明红色:

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

就这么做

# thicker border
draw.text((x-1, y-1), text, font=font, fill=shadowcolor)
draw.text((x+1, y-1), text, font=font, fill=shadowcolor)
draw.text((x-1, y+1), text, font=font, fill=shadowcolor)
draw.text((x+1, y+1), text, font=font, fill=shadowcolor)

相关问题 更多 >