python批量给图加水印

以上是用python批量给图片添加水印


# -*- coding: utf8 -*-

import os,Image, ImageEnhance

def set_opacity(im, opacity):
    """设置透明度"""

    assert opacity >=0 and opacity < 1
    if im.mode != "RGBA":
        im = im.convert('RGBA')
    else:
        im = im.copy()
    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)
    return im

def watermark(im, mark, position, opacity=1):
    """添加水印"""

    try:
        if opacity < 1:
            mark = set_opacity(mark, opacity)
        if im.mode != 'RGBA':
            im = im.convert('RGBA')
        #if im.size[0] < mark.size[0] or im.size[1] < mark.size[1]:
            #print "The mark image size is larger size than original image file."
            #return False

        #设置水印位置
        if position == 'left_top':
            x = 0
            y = 0
        elif position == 'left_bottom':
            x = 0
            y = im.size[1] - mark.size[1]
        elif position == 'right_top':
            x = im.size[0] - mark.size[0]
            y = 0
        elif position == 'right_bottom':
            x = im.size[0] - mark.size[0]+5
            y = im.size[1] - mark.size[1]-16
        else:
            x = (im.size[0] - mark.size[0]) / 2
            y = (im.size[1] - mark.size[1]) / 2

        layer = Image.new('RGBA', im.size,)
        layer.paste(mark,(x,y))
        return Image.composite(layer, im, layer)
    except Exception as e:
        print ">>>>>>>>>>> WaterMark EXCEPTION:  " + str(e)
        return False

def water(filename,mark):
    try:
        im = Image.open(filename) #原图
        image = watermark(im, mark, 'right_bottom', 1)
        image.save(filename)
        #image.show()
    except Exception as e:
        print ">>>>>>>>>>> WaterMark save:  " + str(e)
        return False
    
def dirlist(path,mark):
    global num
    filelist =  os.listdir(path)
    for filename in filelist:
	filepath = os.path.join(path, filename)
	if os.path.isdir(filepath):
	    dirlist(filepath,mark)
	else:
	    water(filepath,mark)
	    num += 1
	    print filepath, num

num = 0
if __name__ == '__main__':
    water_path = "E:/water/logo.jpg"
    dir_path = "H:/hx/bj/"
    mark = Image.open(water_path) #水印
    dirlist(dir_path,mark)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值