原图:
效果图:
from PIL import Image, ImageDraw, ImageFont
'''
pos x1,y1,x2,y2矩形坐标对角点
'''
def drawRect(img, pos, **kwargs):
transp = Image.new('RGBA', img.size, (0,0,0,0))
draw = ImageDraw.Draw(transp, "RGBA")
draw.rectangle(pos, **kwargs)
img.paste(Image.alpha_composite(img, transp))
def watermark(img_path,word):
# 打开图片
img1 = Image.open(img_path)
# 图片的颜色模式必须是RBGA,不然不能文字半透明
img1 = img1.convert('RGBA')
width,height = img1.size
# 计算页面高度 灰条为高度的1/5 当然
scale = height/2 - height/10
drawRect(img1,(0,scale,width,scale+ height/5), fill=(0,0,0,150))
draw = ImageDraw.Draw(img1)
# 字体大小为灰色快的一半
font_size = int(height/10)
font = ImageFont.truetype(r'./font/SourceHanSansCN-Normal.otf', font_size) # 字体大小
# 计算字体位置。应为len()/4中文/2
f_w = width/2 - len(word)/2*font_size
f_h = scale + height/10 - font_size/2
# 字体坐标
font_coordinate = (int(f_w),int(f_h))
draw.text(font_coordinate, word,font=font, fill=(255, 255, 255, 100))
return img1
if __name__ == "__main__":
img = watermark('./img/3.jpg','面向百度')
img.show()