Home > OS >  How would I use PIL to "extend" an image, and then draw a black rectangle with text on it?
How would I use PIL to "extend" an image, and then draw a black rectangle with text on it?

Time:07-04

Basically, what I want to do with Pillow is:

I want to get an image, and then extend the size of the image from the bottom so I'm able to fit a black rectangle with a four digit code on it. How would I do this? I tried to, but my text ended up being, for some reason, extremely small and unreadable and my rectangle wasn't perfect.

If it makes it easier, here's my image: enter image description here

CodePudding user response:

You could create a new black image, paste the desired image and add text.

from PIL import Image, ImageFont, ImageDraw 


base_img = Image.open('tmp.jpg')
base_size = base_img.size
new_size = (base_size[0], base_size[1]   150)
img = Image.new("RGB", new_size)
img.paste(base_img, (0, 0))

draw = ImageDraw.Draw(img)
font = ImageFont.truetype("microsoftsansserif.ttf", 145) # (<font-file>, <font-size>)d
draw.text((base_size[0] // 2 - 150, base_size[1]),"GVVL",(255,255,255),font=font) # (x, y),"text",(r,g,b)
img.save('out.jpg')

Result

  • Related