How to generate transparent watermark automatically by using python

This article shows how to generate transparent watermark automatically by using python.

If you want to generate watermark by using python script, you can read on.

1. The environment

  • Python 3.6.5
  • Pip 10

2. Install Pillow

You must install Pillow to continue, Pillow is a python library to process images.

➜  bswen: pip install pillow

If you encounter any ssl issue when installing pillow, you can view this articleHow to solve the pip and ssl version problem when install Pillow on MacOS.

Verify your pillow is ok:

➜  bswen: python
Python 3.6.5 (default, Apr 22 2018, 14:43:19)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL

If there is no errors when import PIL , then you can go on.

3. Write the script

from PIL import Image
import sys
def watermark_with_transparency(input_image_path,
    base_image ="RGBA") # convert to RGBA is important

    watermark ="RGBA")
    width, height = base_image.size
    mark_width, mark_height = watermark.size
    position = (width-mark_width,height-mark_height) # put the watermark at the lower-right corner

    transparent ='RGBA', (width, height), (0,0,0,0))
    transparent.paste(base_image, (0,0))
    transparent.paste(watermark, position, mask=watermark)
if __name__ == '__main__':
    if len(sys.argv)<=1:
        print('python <the_image_name>')
    the_image = sys.argv[1]
    if the_image is None or len(the_image)==0:
        print('python <the_image_name>')
python sbm1.png

The origin image : origin image before watermark

The watermarked image: origin image after watermark

You can find detail documents about the python pip here: