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,
output_image_path,
watermark_image_path
):
base_image = Image.open(input_image_path).convert("RGBA") # convert to RGBA is important
watermark = Image.open(watermark_image_path).convert("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 = Image.new('RGBA', (width, height), (0,0,0,0))
transparent.paste(base_image, (0,0))
transparent.paste(watermark, position, mask=watermark)
transparent.show()
transparent.save(output_image_path)
if __name__ == '__main__':
if len(sys.argv)<=1:
print('python watermark.py <the_image_name>')
exit(1)
the_image = sys.argv[1]
if the_image is None or len(the_image)==0:
print('python watermark.py <the_image_name>')
exit(1)
else:
watermark_with_transparency('./images_origin/%s'%the_image,
'./images_watermarked/%s'%the_image,
'./logo.png')
python watermark.py sbm1.png
The origin image :
The watermarked image:
You can find detail documents about the python pip here: