用Python给(blog)图片加上水印

Last updated on 2 years ago

原文:州的先生 使用Python编写批量添加图片水印程序:一、代码方案 https://zmister.com/archives/990.html

准备

1、备好自己要加的水印图片,可以用PS制作或者网上找自己喜欢的。

2、待加水印图片

3、编写以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
import sys
import glob
import os, traceback, time
# from operator import lt
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont


# get image path
def get_folder(fpath, wm_file, save_path):
try:
img_suffix_list = ['png', 'PNG','jpg', 'JPG', 'bmp']
for i in os.listdir(fpath):
if i.split('.')[-1] in img_suffix_list:
img_path = fpath + '/' + i
img_water_mark(img_file=img_path, wm_file=wm_file, save_path=save_path)
time.sleep(0.3)
except Exception as e:
print(traceback.print_exc())

# add water mark
def img_water_mark(img_file, wm_file, save_path):
try:
img = Image.open(img_file)
watermark = Image.open(wm_file)
img_size = img.size
wm_size = watermark.size
# print(wm_size)

# if img_size[0] & lt & wm_size[0]:
watermark.resize(tuple(map(lambda x: int(x * 0.5), watermark.size)))
print('image size:', img_size)
# default, the watermark position is set to the lower right corner
wm_position = (img_size[0] - wm_size[0], img_size[1] - wm_size[1])
# new layer
layer = Image.new('RGBA', img.size)
# Add watermark picture to layer
layer.paste(watermark, wm_position)
mark_img = Image.composite(layer, img, layer)
new_file_name = img_file.split('/')[-1]
mark_img.save(save_path + new_file_name)
except Exception as e:
print(traceback.print_exc())

def watermarks(post_name):
if post_name == 'all':
post_name = '*'
dir_name = './sourceimg/' + post_name + '/*'
for files in glob.glob(dir_name):
im = Image.open(files)
if len(im.getbands()) < 3:
im = im.convert('RGB')
print(files)
font = ImageFont.truetype('STSONG.TTF', max(30, int(im.size[1] / 20)))
draw = ImageDraw.Draw(im)
draw.text((im.size[0] / 2, im.size[1] / 2), u'@kuibarj.top', fill=(0, 0, 0), font=font)
im.save(files)


if __name__ == '__main__':
if len(sys.argv) == 2:
print("\n[*] Compositing please wait...")
get_folder(fpath=r"./sourceimg/image/", wm_file=r"./resources/blogo.png", save_path=r"./sourceimg/image/")
watermarks(sys.argv[1])
print('[+] add logo success!')
else:
print('[usage] <input>')
print('\netc: python3 watermark.py all')

加上水印后

END

原作者写的代码中,是有个判断图片是否小于水印图片,这里我把其注释了,因为在自己的环境上代码跑不起来。

完整代码内容 https://github.com/Kuibagit/BlogImageWatermark


用Python给(blog)图片加上水印
https://guosec.online/posts/ba9aa5f5.html
Posted on
July 2, 2019
Updated on
July 2, 2022
Licensed under
本博客所有文章除特别声明外,均采用  协议,转载请注明出处!