Search code examples
pythonpycharm

AttributeError: 'str' object has no attribute 'rotate'


I was creating image over text , Need to rotate in 360 degree , Got this error , Please help me out

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont, ImageOps

img = Image.open('cupcake toppe.png')


I1 = ImageDraw.Draw(img)


myFont2 = ImageFont.truetype('arial.ttf', 15)


text2 = "3345"

img1 = text2.rotate(17.5,  expand=1)

I1.text((50, 15), text2, img1, font=myFont2, fill=(0, 0, 0))

img.show()

Solution

  • I know about this method, I hope it will help you:

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

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

    For convenience, we will fix the height of the line, since Pillow changes it depending on the text, which may interfere with 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, which will fit any letters, we will use the undocumented getmetrics method for some reason:

    line_height = sum(font.getmetrics())  # 33 + 8 = 41
    

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

    fontimage = Image.new('L', (font.getsize(label)[0], line_height))
    ImageDraw.Draw(fontimage).text((0, 0), label, fill=255, font=font)
    

    Now let's turn it around. We need to add expand=True to increase the size of the image so that the rotated text fits.

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

    Now, we overlay the image on the original

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

    The first argument specifies the image that we are applying. 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.