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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
#! /usr/bin/env python2.7
# -*- coding: utf-8 -*-
import
Image
import
os
class
WaterMark(
object
):
'''
水印工具类,提供基本的给图片打水印的功能
使用:
marker = WaterMark(path) # path为水印图片的路径
marker.mark(pic) # pic为待打水印的图片
marker.mark_dir(pic_dir) # pic_dir为待打水印的目录
'''
POSITION_TOP_LEFT
=
0
POSITION_TOP_RIGHT
=
1
POSITION_BOTTOM_LEFT
=
2
POSITION_BOTTOM_RIGHT
=
3
# 在原图片中打水印的区域
box
=
(
0
,
0
,
0
,
0
)
backup_suffix
=
'.bak'
def
_gen_mosaic(
self
, arg):
'''打开水印图片'''
try
:
mosaic
=
Image.
open
(arg).convert(
'RGBA'
)
except
IOError:
print
'cannot convert file.'
return
mosaic
def
__init__(
self
,
*
args,
*
*
kwargs):
if
args:
arg
=
args[
0
]
self
._mosaic
=
self
._gen_mosaic(arg)
def
_locate(
self
, image, position
=
POSITION_BOTTOM_RIGHT):
'''定位原图片打水印的位置'''
w, h
=
self
._mosaic.size
i_w, i_h
=
image.size
if
position
=
=
self
.POSITION_TOP_LEFT:
self
.box
=
(
0
,
0
, w, h)
elif
position
=
=
self
.POSITION_TOP_RIGHT:
self
.box
=
(i_w
-
w,
0
, i_w, h)
elif
position
=
=
self
.POSITION_BOTTOM_LEFT:
self
.box
=
(
0
, i_h
-
h, w, i_h)
elif
position
=
=
self
.POSITION_BOTTOM_RIGHT:
self
.box
=
(i_w
-
w, i_h
-
h, i_w, i_h)
else
:
self
.box
=
(
0
,
0
,
0
,
0
)
def
mark(
self
, path, position
=
POSITION_BOTTOM_RIGHT):
'''给单个图片打水印'''
try
:
img
=
Image.
open
(path)
except
IOError:
return
None
if
img.size[
0
] <
self
._mosaic.size[
0
]:
print
'width'
, img.size[
0
],
self
._mosaic.size[
0
]
return
None
if
img.size[
1
] <
self
._mosaic.size[
1
]:
print
'height'
, img.size[
1
],
self
._mosaic.size[
1
]
return
None
img_area
=
img.size[
0
]
*
img.size[
1
]
mosaic_area
=
self
._mosaic.size[
0
]
*
self
._mosaic.size[
1
]
ratio
=
4
if
img_area < mosaic_area
*
ratio:
return
None
self
._locate(img, position)
layer
=
Image.new(
'RGBA'
, img.size, (
0
,
0
,
0
,
0
))
layer.paste(
self
._mosaic,
self
.box)
return
Image.composite(layer, img, layer)
def
mark_dir(
self
, path, backup
=
False
, position
=
POSITION_BOTTOM_RIGHT):
'''批量打水印'''
for
root, dirs, files
in
os.walk(path):
for
f
in
files:
path
=
os.path.join(root, f)
if
path.endswith(
self
.backup_suffix):
continue
print
path
f_marked
=
self
.mark(path)
if
not
f_marked:
continue
if
backup:
os.rename(path, path
+
self
.backup_suffix)
f_marked.save(path, f_marked.
format
)
def
test():
'''
用来测试打水印功能
命令行使用:
python watermark.py 水印图片路径 待打水印图片的目录
'''
import
sys
if
len
(sys.argv) <
3
:
return
False
mosaic_path
=
sys.argv[
1
]
directory
=
sys.argv[
2
]
marker
=
WaterMark(mosaic_path)
marker.mark_dir(directory, backup
=
True
)
if
__name__
=
=
'__main__'
:
test()
|
python,PIL给图片加水印
最新推荐文章于 2022-08-10 12:58:11 发布