PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 29, 2022

[FIXED] How would I use PIL to "extend" an image, and then draw a black rectangle with text on it?

 July 29, 2022     image, python, python-imaging-library     No comments   

Issue

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: https://i.stack.imgur.com/o9eYr.jpg

And here's what I want the end result to be: https://i.stack.imgur.com/GZ4uu.jpg (take a look at the bottom of the image)


Solution

I would suggest ImageOps.expand to expand your canvas:

#!/usr/bin/env python3

from PIL import Image, ImageDraw, ImageFont, ImageOps

# Load image
im = Image.open('o9eYr.jpg')

# Define font size, and annotation and height of padding above and below annotation
fontSize   = 130
annotation = "GVVL"
padding    = 20

# Load font and work out size of annotation
font = ImageFont.truetype("/System/Library/Fonts//Menlo.ttc", fontSize)
tw, th = font.getsize(annotation)

# Extend image at bottom and get height and width of new canvas
extended = ImageOps.expand(im, border=(0,0,0,th+2*padding), fill=(0,0,0))
w, h = extended.size

# Get drawing context and annotate
draw = ImageDraw.Draw(extended)
draw.text(((w-tw)//2, h-th-padding), annotation,(255,255,255),font=font)
extended.save('result.jpg')

enter image description here



Answered By - Mark Setchell
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing