gpt4 book ai didi

python - 如何为draw.text中的文本分配不同的颜色

转载 作者:太空宇宙 更新时间:2023-11-03 19:51:50 28 4
gpt4 key购买 nike

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

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,则它不能很好地掩盖原始图像并给出错误。

最佳答案

您可以按照下面post中的解决办法:

只需将 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()

结果:
enter image description here

关于python - 如何为draw.text中的文本分配不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59783167/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com