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

Python PIL 图片水印添加

2015-12-21 17:17 603 查看
非常感谢 这个博主 http://linsir.org/post/python-add-watermark-with-PIL 
之前写的一个为图片增加水印的小脚本不好用了一刚!!

原来的小脚本,

from PIL import Image, ImageDraw, ImageFont
import time

def watermark(img, img_ed, date, number, fnt):
"""Adds a watermark to an image."""
#draw the watermark on the empty pic
img_draw = ImageDraw.Draw(img_ed)
img_draw.text((220, 293), date, font=fnt, fill=(255,255,255,255))
img_draw.text((280, 10), number, font=fnt, fill=(255,255,255,255))

#out = Image.alpha_composite(img, img_ed)
out = Image.composite(img, img_ed, img)
h, w = out.size

out = out.resize((270, 270))
#out.show()
#exit()
out.save("1.gif")
print "saved as gif"
exit()
#raw_input("wait..")

def daily():
img = Image.open("供应链me.jpg").convert('RGBA')
#img.save("1.gif")
#exit()
date = time.strftime("%Y/%m/%d")
number = raw_input("Input the number please:")

#make a blank image for the text, initialized to transparent text color
img_ed = Image.new('RGBA', img.size, (255,255,255,0))

h,w = img.size
#print "h = :", h
#print "w = :", w

#draw txt on the pic
fnt = ImageFont.truetype('D:\E\myexp\运维日报\simkai.ttf',20)

watermark(img, img_ed, date, number, fnt)

if __name__ == '__main__':
daily()
报错

 "Traceback (most recent call last):

  File "D:\E\myexp\operationdairy\dr_pic_2.py", line 44, in <module>

    daily()

  File "D:\E\myexp\operationdairy\dr_pic_2.py", line 40, in daily

    watermark(img, img_ed, date, number, fnt)

  File "D:\E\myexp\operationdairy\dr_pic_2.py", line 11, in watermark

    out = Image.alpha_composite(img, img_ed)

AttributeError: 'module' object has no attribute 'alpha_composite'"

自我感觉应该是PIL库升级了,然后 alpha_composite 方法不存在了吧,于是抄了如下的代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-11-29 19:09:59
# @Author  : Linsir (vi5i0n@hotmail.com)
# @Link    : http://linsir.org 
import Image, ImageEnhance, ImageDraw, ImageFont
import time

def text2img(text, font_color="White", font_size=20):
"""生成内容为 TEXT 的水印"""

font = ImageFont.truetype('MSYH.ttc', font_size)
#多行文字处理
text = text.split('\n')
mark_width = 0
for  i in range(len(text)):
(width, height) = font.getsize(text[i])
if mark_width < width:
mark_width = width
mark_height = height * len(text)

#生成水印图片
mark = Image.new('RGBA', (mark_width,mark_height))
draw = ImageDraw.ImageDraw(mark, "RGBA")
draw.setfont(font)
for i in range(len(text)):
(width, height) = font.getsize(text[i])
draw.text((0, i*height), text[i], fill=font_color)
return mark

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] + 10
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 main():
#text = u'Linsir.水印.\nvi5i0n@hotmail.com'
# text = open('README.md').read().decode('utf-8')
# print text

text1 = raw_input("Input the number please:")
text2 = time.strftime("%Y/%m/%d")
text2 = text2.split('\n')
text2 = text2[0]

im = Image.open('D:/E/myexp/operationdairy/SCMPIC.jpg')
mark1 = text2img(text1)
mark2 = text2img(text2)

image = watermark(im, mark1, 'right_top', 0.9)
image = watermark(image, mark2, 'right_bottom', 0.9)

if image:
image.save('D:/E/myexp/operationdairy/watermark.png')
image.show()
else:
print "Sorry, Failed."

if __name__ == '__main__':
main()


就OK了,感觉还是记不住,抄抄代码还是OK的....

顺便记录一个网站,说是每天一个Python 程序 https://github.com/Yixiaohan/show-me-the-code 试试吧,2015年不要走,25岁不要走 _(:зゝ∠)_



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: