? ? ? ? 现在网络的图片基本都是带有水印的,也学一下怎么个添加,代码注释掉的都是调试过程的显示,感兴趣的可以打开瞅瞅,图片水印位置是固定在右下角的,代码的12-19行可以调整。
# -*- coding: utf-8 -*-
import os
import time
from PIL import Image
def watermark_photo(input_image_path,watermark_image_path,output_image_path):
base_image = Image.open(input_image_path)
watermark = Image.open(watermark_image_path).convert("RGBA")
#base_image.show() # 显示图片
#watermark.show() # 显示水印
# 水印打在图片的位置 设置水印大小
position = base_image.size
newsize = (int(position[0]*8/100),int(position[0]*8/100))
new_position = position[0]-newsize[0]-20, position[1]-newsize[1]-20
print(position)
print(new_position)
print(newsize)
watermark = watermark.resize(newsize)
# 做一个透明的底片 大小同图片
transparent = Image.new(mode='RGBA', size=position, color=(0,0,0,0))
#transparent.show() # 显示
# 向底片添加图片
transparent.paste(base_image, (0,0))
#transparent.show() # 显示
# 向底片添加水印
transparent.paste(watermark, new_position, watermark)
#transparent.show() # 显示
image_mode = base_image.mode
if image_mode == 'RGB':
transparent = transparent.convert(image_mode)
else:
transparent = transparent.convert('P')
transparent.save(output_image_path,optimize=True,quality=100)
print("Saving " + output_image_path + " ...... ")
folder = "/home/aiaike/ausr/Python/miniProgram"
watermark = "/home/aiaike/ausr/Python/miniProgram/dfjbgljadfa.jpg"
os.chdir(folder)
files = os.listdir(os.getcwd())
if not os.path.isdir("output"):
os.mkdir("output")
for f in files:
if os.path.isfile(os.path.abspath(f)):
if f.endswith(".png") or f.endswith(".jpg"):
print(os.path.abspath(f))
watermark_photo(f, watermark, "output/"+f)
#time.sleep(27)
?
|