1

I'm adding a text on an image at a position (x,y) and then drawing a rectangle around it (x,y,x+text_width,y+text_height). Now I'm rotating the image by an angle of 30. How can I get the new coordinates ?

from PIL import Image
im = Image.open('img.jpg')
textlayer = Image.new("RGBA", im.size, (0,0,0,0))
textdraw = ImageDraw.Draw(textlayer)
textsize = textdraw.textsize('Hello World', font='myfont.ttf')
textdraw.text((75,267), 'Hello World', font='myfont.ttf', fill=(255,255,255))
textlayer = textlayer.rotate(30)

I tried this . But I'm not getting the point correctly. Can anyone point me what I'm doing wrong.

textpos = (75,267)
theta = 30
x0,y0 = 0,0
h = textsize[0] - textsize[1]
x,y = textpos[0], textpos[1]
xNew = (x-x0)*cos(theta) - (h-y-y0)*sin(theta) + x0
yNew = -(x-x0)*sin(theta) - (h-y-y0)*cos(theta) + (h-y0)
Rahul
  • 3,208
  • 8
  • 38
  • 68
  • Could you include missing code? For example, you refer to "textpos", but that variable is not defined. – payne Aug 18 '18 at 12:07

1 Answers1

0

In PIL, the rotation happens about the center of the image. So considering your center of the image is given by:

cx = int(image_width / 2)
cy = int(image_height / 2)

a specified rotation angle:

theta = 30

and given coordinates (px, py), The new coordinates can be obtained using the following equation:

rad = radians(theta)

new_px = cx + int(float(px-cx) * cos(rad) + float(py-cy) * sin(rad))
new_py = cy + int(-(float(px-cx) * sin(rad)) + float(py-cy) * cos(rad))

Please note that the angle must be specified in radians, not degrees.

This answer is inspired from this following blog-post.

Koustav
  • 733
  • 1
  • 6
  • 21