如何利用python给图片添加半透明水印

yipeiwu_com6年前Python基础

前言

本文主要给大家介绍了关于python图片添加半透明水印的相关资料,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧

示例代码:

# coding:utf-8

from PIL import Image, ImageDraw, ImageFont


def add_text_to_image(image, text):
 font = ImageFont.truetype('C:\Windows\Fonts\STXINGKA.TTF', 36)

 # 添加背景
 new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0))
 new_img.paste(image, image.size)

 # 添加水印
 font_len = len(text)
 rgba_image = new_img.convert('RGBA')
 text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
 image_draw = ImageDraw.Draw(text_overlay)

 for i in range(0, rgba_image.size[0], font_len*40+100):
  for j in range(0, rgba_image.size[1], 200):
   image_draw.text((i, j), text, font=font, fill=(0, 0, 0, 50))
 text_overlay = text_overlay.rotate(-45)
 image_with_text = Image.alpha_composite(rgba_image, text_overlay)

 # 裁切图片
 image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))
 return image_with_text


if __name__ == '__main__':
 img = Image.open("test.jpg")
 im_after = add_text_to_image(img, u'测试使用')
 im_after.save(u'测试使用.png')

效果图:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

python将四元数变换为旋转矩阵的实例

如下所示: import numpy as np from autolab_core import RigidTransform # 写上用四元数表示的orientation和xy...

python实现画圆功能

python实现画圆功能

本文实例为大家分享了python实现画圆功能的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- """ __author__= 'Du' __...

Python切片操作深入详解

本文实例讲述了Python切片操作。分享给大家供大家参考,具体如下: 我们基本上都知道Python的序列对象都是可以用索引号来引用的元素的,索引号可以是正数由0开始从左向右,也可以是负数...

python for 循环获取index索引的方法

使用 enumerate 函数 可以返回下标。 例如 for inx, val in enumerate(['uyy', 'dfdf']): print(inx) pri...

python石头剪刀布小游戏(三局两胜制)

Python 石头剪刀布小游戏(三局两胜),供大家参考,具体内容如下 import random all_choioces = ['石头', '剪刀', '布'] win_list...