[Answer]-How to add custom bottom to every image in Django

1πŸ‘

βœ…

In my own situations I have occasionally looked into django-imagekit and realized that I needed to just process things myself using PIL/Pillow. The following code has not been 100% tested, so consider it a rough guide rather than an exact roadmap:

from PIL import Image, ImageDraw, ImageFont

#open your original image, get it's width
img_src = Image.open('my_img.jpg')
xsize, ysize = img_src.size()

#create a new image that's just a little bit taller than the src image
img_text = Image.new("RGB",(xsize,yszize+30))

#paste the old image into the new one, flush at the top
img_text.paste(img_src,(0,0))

#Load font, draw to the bottom of the new image
#note that you must have the font file in your project
font = ImageFont.truetype("Arial.ttf", 16)
draw = ImageDraw.Draw(img_text)
draw.text((0, xsize),"Put your text here",(255,255,255),font=font)

img_text.save("appended_image.jpg")

If you want to add the new image to an actual Django image field, the saving is a bit more complicated (see this answer, for example, on how to go about doing that)

πŸ‘€MBrizzle

0πŸ‘

django-imagekit supports custom processors. All you have to do is define a class with a process method that both accepts and returns an image. This way you’ll get all the benefit of IK (model fields, caching, etc).

Leave a comment