您的位置:首页 > 编程语言 > Python开发

python批量给图加水印

2016-04-14 10:34 429 查看
以上是用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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: