In this project we are going to learn how we can add text to an image.
This can be used
- to create an Image quote in Python.
- to create watermark in Python
We will be using PIL (pillow) Library in this project
To create Image we will use Image and ImageDraw module
To set fonts we will use ImageFont module
and
To write text on an image we will use multiline_text() method if ImageDraw module
To Create an Image quote we require a background Image of our own choice on which we can write our quote
Lets define the tasks to be be performed for this project and work accordingly
Task 0: Import libraries:
from PIL import Image, ImageDraw, ImageFont
Task 1: Read an Image
imgObject=Image.open('full or relative path of your image')
Image.open() reads the image and returns an Image object
Task 2: Set the font of the text you want to add to the image
font_object = ImageFont.truetype("E:\\Font\\sunday-spring\\Sunday Spring.ttf", 350)
Download any font file of your own choice from google and specify the path inside truetype() method of ImageFont class
If you font file is with extension .otf then you can call opentype() method of ImageFont class
font_object = ImageFont.opentype("E:\\Font\\sunday-spring\\Sunday Spring.otf", 350)
Task 3 : Creating ImageDraw object to draw text on an Image
drawing_object = ImageDraw.Draw(imgObject)
Inside the ImageDraw.Draw we need to specify image object so that we can bind the drawing pen to the image
Task 4: Write the text
drawing_object.multiline_text((400,800), "MV's Code Guide", font=font_object, fill=(0, 0, 0))
With the drawing object call multiline_text() method to add multiline text or else you can call text() method to add single line text
Inside multiline_text() method :
- First parameter is xy coordinate of Top left corner of the text.
- Second Parameter is- Text to be drawn.
- Third parameter is : font – An
ImageFont
instance
- Fourth parameter is : fill – Color to use for the text.
- spacing – The number of pixels between lines.
- align –
"left"
,"center"
or"right"
.
- direction – Direction of the text. It can be
"rtl"
(right to left),"ltr"
(left to right) or"ttb"
(top to bottom). Requires libraqm.
Task 5: Save the new Image with text:
drawing_object.save('new_image.jpg')
Full code:
#Example: Create Image Quote from PIL import Image, ImageDraw, ImageFont # create an image object #imgObject = Image.new("RGB", (500, 500), (255, 255, 255))
imgObject=Image.open('Path of Image')
# get a font object
font_object = ImageFont.truetype("E:\\Font\\sunday-spring\\Sunday Spring.ttf", 350)
# get a drawing context
drawing_object = ImageDraw.Draw(imgObject)
# draw multiline text
drawing_object.multiline_text((400,800), "MV's Code Guide", font=font_object, fill=(0, 0, 0))
# save the image
drawing_object.save('new_image.jpg')
No comments:
Post a Comment