Python pil 绘制不同颜色的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15026178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:08:13 来源:igfitidea点击:
pil draw text with different colors
提问by Frankenstein Palinskij
Hi to draw three different text with different options for ex:
嗨,用不同的选项为 ex 绘制三个不同的文本:
- text-number-1 , font=arial, color=red
- text-number-2 , font=veranda, color=blue, size=30
- text-number-3 , font=tahoma, color=green, size=40 , align=center
- text-number-1 , font=arial, color=red
- text-number-2 , font=veranda, color=blue, size=30
- 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'>");
回答by MatthieuW
The "fill" parameter should be a tuple with 4 number, as you use a RGBA colormode.
“fill”参数应该是一个有 4 个数字的元组,因为你使用的是 RGBA 颜色模式。
For opaque red:
对于不透明的红色:
draw.text((margin, offset), line, font=font, fill=(255,0,0,255) )
回答by redreamality
simply do this
简单地做这个
# 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)
回答by leenremm
Use hex value for colour, as follows:
使用十六进制值作为颜色,如下所示:
draw.text((margin, offset), line, font=font, font=font, fill="#000")

