Reputation: 552
I've width and height of the image.
img = Image.open(img_src)
width, height = img.size
font = ImageFont.truetype("MuseoSansCyrl_0.otf", 100)
text_w, text_h = draw.textsize(title, font)
I'm trying to find a generic way to add a text to image at the bottom middle.
Here is the function I've wrote:
def process_img(img_src, title, background):
img = Image.open(img_src, 'r')
draw = ImageDraw.Draw(img)
w, h = img.size
font = ImageFont.truetype("MuseoSansCyrl_0.otf", 100)
text_w, text_h = draw.textsize(title, font)
draw.text((REQ_WIDTH, REQ_HEIGHT), title, (255,255,255), font=font)
img.save(img_src)
return img_src
Is there any way I can get the REQ_WIDTH and REQ_HEIGHT ?
Upvotes: 5
Views: 6235
Reputation: 123541
The names you have for the needed variables — REQ_WIDTH
and REQ_HEIGHT
— are a little misleading because they're not a width and height, they are the "xy anchor coordinates of the text" relative to its top left corner by default — see documentation — in other words, its position.
You just need to do a little math:
X_POSN = h - text_h
Y_POSN = w//2 - text_w//2 # Or (w - text_w) // 2
draw.text((X_POSN, Y_POSN), title, (255,255,255), font=font)
Upvotes: 4
Reputation: 110666
You had already placed a call to draw.textsize
, which returns you the Width and Height the final text will have - from that point, you just thave to calculate the top-left corner where to render your text like this:
Top will be your image_height - text_height, left will be your image_width/2 - text_width / 2 - thus, your rendering call becomes simply:
draw.text(((w - text_w) // 2, h - text_h), title, (255,255,255), font=font)
(Note that draw.text
includes an optional "anchor" argument - but the possible values for it are not documented, nor the documentation states whether it is actually implemented. If it is implemented, and there is a value that represents (horizontal_center, bottom) as the Anchor, you should only have to pass the image_width / 2 and image_height, without needing to call draw.textsize
)
Upvotes: 4