Python 如何为draw.text中的文本指定不同的颜色

Python 如何为draw.text中的文本指定不同的颜色,python,image,Python,Image,我需要将文本写入图像,我就是这样做的: image = Image.open(background) draw = ImageDraw.Draw(image) text = str(randint(0, 9999999)) # specified font size fs = 52 font = ImageFont.truetype('font.ttf', 52) font_size = font.getsize(text) draw.text((x, y), text, fi

我需要将文本写入图像,我就是这样做的:

image = Image.open(background)  

draw = ImageDraw.Draw(image)  
text = str(randint(0, 9999999)) 
# specified font size 
fs = 52
font = ImageFont.truetype('font.ttf', 52)  
font_size = font.getsize(text)
draw.text((x, y), text, fill =(64,64,64), font = font, align ="right")  
但我需要旋转这个文本,除了创建一个图像外,我找不到任何东西。将文本写入其中,旋转这个图像,然后将其粘贴到原始图像

txt=Image.new('L', (w,h))
d = ImageDraw.Draw(txt)
d.text( (0, 0), text,  font=font, fill=186)
w=txt.rotate(-3,  expand=1)

px, py = x, y
sx, sy = w.size
image.paste(w, (px, py, px + sx, py + sy), w)

问题是,我不能用和前面文本相同的灰色填充它。换句话说,我想给它指定一个灰色,但不能这样做。如果我创建这个图像为RGB,那么它不能很好地掩盖原始图像,并给出错误

您可以遵循以下解决方案:

只需将
image.paste(w,(px,py,px+sx,py+sy),w)替换为
image.paste(ImageOps.colorize(w,(0,0,0),(64,64,64)),(px,py,px+sx,py+sy),w)

示例代码:

from PIL import Image, ImageDraw, ImageFont, ImageOps
from numpy import random
from random import randint

x, y = 100, 100

background = 'chelsea.png'

image = Image.open(background)

draw = ImageDraw.Draw(image)
text = str(randint(0, 9999999))
# specified font size
fs = 52
font = ImageFont.truetype('DejaVuSans-Bold.ttf', 52)
font_size = font.getsize(text)
# draw.text((x, y), text, fill =(64,64,64), font = font, align ="right")

w, h = 300, 100
txt = Image.new('L', (w, h))
d = ImageDraw.Draw(txt)
d.text((0, 0), text,  font=font, fill=255) #  fill=255 instead of 186
w = txt.rotate(-20, expand=1) #Just for example, -3 is replaces by -20

px, py = x, y
sx, sy = w.size
# image.paste(w, (px, py, px + sx, py + sy), w)
image.paste(ImageOps.colorize(w, (0,0,0), (64,64,64)), (px, py, px + sx, py + sy), w)

image.show()
结果: