3

I need to write text to image and this is how I did it:

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

But I needed to rotate this text and I couldn't find anything except to create an image write text to it, rotate this image and then paste it to original image.

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)

Problem is that I can't fill it with the same gray color that I did with earlier text. In other words I want to assign it a gray color but can't do it. If I create this image as RGB then it doesn't mask well to the original image and gives error.

meu
  • 125
  • 2
  • 10

1 Answers1

1

You can follow the solution in the following post:

Just replace image.paste(w, (px, py, px + sx, py + sy), w) with image.paste(ImageOps.colorize(w, (0,0,0), (64,64,64)), (px, py, px + sx, py + sy), w).

Sample code:

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()

Result:
enter image description here

Rotem
  • 30,366
  • 4
  • 32
  • 65