Hello!
I want to turn the text to 80 degrees, how can this be done?
Here is the code:

from PIL import Image, ImageGrab, ImageFont, ImageDraw txt = Image.open("screen.png") fnt = ImageFont.truetype("arial.ttf", 36) d = ImageDraw.Draw(txt) d.text((740,430), 'hello world', font=fnt, fill=('#1f6992')) #значения "740" и "430" - это значения по иксу и игрику, а как по углу задать? txt.save("file.png", "PNG") 

thank

1 answer 1

The text that we will draw, and the font to it:

 label = 'Hello!' font = ImageFont.truetype('arial.ttf', 36) 

For convenience, let's fix the line height, since Pillow changes it depending on the text, which may interfere with the rotation. In particular, the height of the text A is 33 pixels, and the height of the text q is already 40 pixels due to the stick sticking down. To get the exact height of the entire string, into which any letters fit, we use for some reason the undocumented getmetrics method:

 line_height = sum(font.getmetrics()) # в нашем случае 33 + 8 = 41 

Now draw the text on a separate clean picture. Here we apply a little trick: the picture will be in shades of gray and denote the alpha channel. Black color (0) - full transparency, white (255) - full opacity. To make the picture the size of our text, we will get its width using the getsize method, and take the height from our permanent line_height .

 # Создаём пустую чёрную картинку fontimage = Image.new('L', (font.getsize(label)[0], line_height)) # И рисуем на ней белый текст ImageDraw.Draw(fontimage).text((0, 0), label, fill=255, font=font) 

(By replacing 255 with another number, you can adjust the transparency of the text.)

Result:

Now turn it around. We need to add expand=True so that the size of the image increases so that the rotated text climbs.

 fontimage = fontimage.rotate(80, resample=Image.BICUBIC, expand=True) 

On the left a good result with expand , on the right a bad one without expand for comparison

Now the resulting image can be superimposed on the original.

 orig = Image.open('original.png') orig.paste((255, 0, 0), box=(0, 0), mask=fontimage) 

The first argument specifies the picture that we apply. Instead, you can specify the color, which I did: this is RGB, which stands for red.

The second argument when feeding him a tuple with two elements indicates the place where the picture will be inserted. It is important to remember that these coordinates will be located upper left corner of the inserted image, and not, for example, the beginning of the text; if you need to insert text above any point, you will have to make additional calculations of the coordinates. Here I just shove everything into the upper left corner.

The third argument is the mask, according to which both pictures will be mixed. As it I use black and white rotated text: black is full transparency, white is opacity.

Result:

Original before insert

After insertion

  • I have already figured out, but thanks anyway) - I TT