1
+ from PIL import Image , ImageDraw , ImageFont
2
+ import os
3
+ import time
4
+
5
+ def process (imgPath , destPath = None , size = (800 ,600 ), text = "" ):
6
+ destPath = destPath if destPath else os .path .join (imgPath ,'out' ,'' )
7
+ if not os .path .isdir (destPath ):
8
+ os .makedirs (destPath )
9
+
10
+ files = [x for x in os .listdir (imgPath ) if os .path .isfile (imgPath + x )]
11
+ print ("待处理文件个数:" , len (files ))
12
+ start = time .time ()
13
+ print ("开始处理 " , start )
14
+ for f in files :
15
+ fext = os .path .splitext (f )[1 ] # 扩展名
16
+ if fext in ['.png' , '.jpg' , '.bmp' , '.jpeg' ]:
17
+ img = Image .open (os .path .join (imgPath , f ))
18
+ img = resize (img , size )
19
+ img = waterMark (img , text )
20
+ img .save (os .path .join (destPath ,f ))
21
+ end = time .time ()
22
+ print ("完成处理 %d, 耗时: %s秒" % (end , int (end - start )))
23
+
24
+
25
+ def resize (img , size ):
26
+ nsize = scale (img .size , size )
27
+ return img .resize (nsize , Image .ANTIALIAS )
28
+
29
+ def waterMark (image , text , font = None ):
30
+ font = font if font else ImageFont .truetype (r"C:\Windows\Fonts\STHUPO.TTF" , 24 )
31
+ mode = image .mode
32
+ if mode != 'RGBA' :
33
+ rgba_image = image .convert ('RGBA' )
34
+ else :
35
+ rgba_image = image
36
+
37
+ text_overlay = Image .new ('RGBA' , rgba_image .size , (255 , 255 , 255 , 0 ))
38
+ image_draw = ImageDraw .Draw (text_overlay )
39
+
40
+ text_size_x , text_size_y = image_draw .textsize (text , font = font )
41
+ # 设置文本文字位置
42
+ text_xy = (rgba_image .size [0 ] - text_size_x - 10 , rgba_image .size [1 ] - text_size_y - 10 )
43
+ # 设置文本颜色和透明度
44
+ image_draw .text (text_xy , text , font = font , fill = (255 , 255 , 255 , 100 ))
45
+
46
+ image_with_text = Image .alpha_composite (rgba_image , text_overlay )
47
+
48
+ if mode != image_with_text .mode :
49
+ image_with_text = image_with_text .convert (mode )
50
+
51
+ return image_with_text
52
+
53
+ def scale (size , lsize ):
54
+ nsize = (size [0 ], size [1 ])
55
+ if nsize [0 ] > lsize [0 ]:
56
+ nsize = (lsize [0 ], int (lsize [0 ]* nsize [1 ]/ nsize [0 ]))
57
+ if nsize [1 ] > lsize [1 ]:
58
+ nsize = (int (lsize [1 ]* nsize [0 ]/ nsize [1 ]), lsize [1 ])
59
+ return nsize
60
+
61
+ if __name__ == "__main__" :
62
+ process ("D:\\ images\\ " , text = "@python技术" )
63
+
0 commit comments