【问题标题】:How to assign different colors to text in draw.text如何为draw.text中的文本分配不同的颜色
【发布时间】:2020-01-17 07:51:03
【问题描述】:

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

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

【问题讨论】:

    标签: python image


    【解决方案1】:

    您可以按照以下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()
    

    结果:

    【讨论】:

      猜你喜欢
      • 2014-09-26
      • 2012-05-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      相关资源
      最近更新 更多