Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A watermark inside a rectangle which filled the certain color

I want to add a watermark at a picture. But just a text, but a rectangle filled with the black color and a white text inside it.

For now, I only can put a text:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

img = Image.open("in.jpg")

draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
#font = ImageFont.truetype("Arialbd.ttf", 66)
draw.text((width - 510, height-100),"copyright",(209,239,8), font=font)
img.save('out.jpg')
like image 673
Alan Coromano Avatar asked Sep 18 '13 10:09

Alan Coromano


1 Answers

This will draw the text on a black rectangular background:

from PIL import Image, ImageFont, ImageDraw

img = Image.open("in.jpg")
width, height = img.width, img.height

draw = ImageDraw.Draw(img)
font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
x, y = (width - 510, height-100)
# x, y = 10, 10
text = "copyright"
w, h = font.getsize(text)
draw.rectangle((x, y, x + w, y + h), fill='black')
draw.text((x, y), text, fill=(209, 239, 8), font=font)
img.save('out.jpg')

enter image description here

Using imagemagick, a better looking watermark could be made with

from PIL import Image, ImageFont, ImageDraw

font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
text = "copyright"
size = font.getsize(text)
img = Image.new('RGBA', size=size, color=(0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fill=(209, 239, 8), font=font)
img.save('label.jpg')

and then calling (through subprocess if you wish) something like

composite -dissolve 25% -gravity south label.jpg in.jpg out.jpg

enter image description here

or if you make label with a white background,

composite -compose bumpmap -gravity southeast label.jpg in.jpg out.jpg

enter image description here


To run these commands from within the Python script, you could use subprocess like this:

import subprocess
import shlex

from PIL import Image, ImageFont, ImageDraw

font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
text = "copyright"
size = font.getsize(text)
img = Image.new('RGBA', size=size, color='white')
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fill=(209, 239, 8), font=font)
img.save('label.jpg')

cmd = 'composite -compose bumpmap -gravity southeast label.jpg in.jpg out.jpg'
proc = subprocess.Popen(shlex.split(cmd))
proc.communicate()
like image 71
unutbu Avatar answered Oct 21 '22 18:10

unutbu