Skip to content

Instantly share code, notes, and snippets.

@shakram02
Created April 28, 2019 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shakram02/427dc6680a5d7de3985e4c18ae217c6b to your computer and use it in GitHub Desktop.
Save shakram02/427dc6680a5d7de3985e4c18ae217c6b to your computer and use it in GitHub Desktop.
Draw black text on a transparent image using PIL
# Source: https://webkul.com/blog/python-imaging-librarypil-examples/
from PIL import Image
from PIL import Image
from PIL import ImageEnhance
from PIL import ImageDraw, ImageFont
img = Image.open("original.jpg")
margin_left,margin_top = img.size
width, height = img.size
image_mode = img.mode
position_left,position_top = 10 ,10
position=(position_left,position_top)
fill = (0,0,0)
#Watermark text color
watermark = Image.new("RGBA", img.size, color = (0, 0, 0, 0))
#Create a Watermark image
waterdraw = ImageDraw.ImageDraw(watermark, "RGBA")
#Create a waterdraw for text
font_path = 'Lato-HaiIta-webfont.ttf'
#Image font path url
txt = 'example.com'
#Watermark text
size = max(1, 100)
#####################################
# this part will reduce the watermark text size
fontsize = 1
img_fraction = .40
font_obj = ImageFont.truetype(font_path, 1)
while font_obj.getsize(txt)[0] < img_fraction*margin_left:
fontsize += 1
font_obj = ImageFont.truetype(font_path, fontsize)
fontsize -= 1
#####################################
font_obj = ImageFont.truetype(font_path, fontsize)
#Create the font obj with fonth type and size
waterdraw.text(position, text = txt, fill=fill,font=font_obj )
positioning = 'horizontal'
if positioning=='vertical':
angle = 45
watermark = watermark.rotate( angle, expand=1 )
transparent_mode = 'RGBA' if image_mode=='P' else 'RGB'
transparent = Image.new(mode = transparent_mode, size =img.size, color = (0,0,0,0))
#Create the new image(result image)
transparent.paste(img, (0,0))
#Paste the original image
transparent.paste(watermark, None, watermark)
#Paste the watermark image
transparent.save("final.jpg",optimize=True,quality=95)
#Save the result image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment