python,PIL给图片加水印

本文介绍了一个用于批量给图片添加水印的Python工具类。该工具提供了灵活的位置选择,并能处理不同大小的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值