python 给图片添加倾斜透明文字水印

注释写在代码里面了,直接改变函数参数就可以使用,使用时注意设置字体大小、透明度、旋转角度等信息,文字位置默认为图片中心,想变动文字位置可根据代码自行修改。 

import numpy as np
from PIL import Image, ImageDraw, ImageFont
import cv2


def rotated_watermark(img_path, text, text_size):
    # 打开图片Image格式
    img1 = Image.open(img_path)
    # 图片的颜色模式设置为RBGA
    img1 = img1.convert('RGBA')
    # 新建一个和原图大小一样的水印覆盖层
    text_overlay = Image.new('RGBA', img1.size, (255, 255, 255, 0))
    # 创建一个画图对象
    image_draw = ImageDraw.Draw(text_overlay)
    # 加载系统字体,设置字体大小
    # font = ImageFont.truetype(r'C:/Windows/Fonts/msyh.ttc', text_size)  # 设置字体大小
    font = ImageFont.truetype(r'Arial.ttf', text_size)
    # 在指定位置画上文字水印
    box = image_draw.textbbox((0, 0), text, font=font)
    text_width, text_height = box[2], box[3]
    x = img1.width / 2 - text_width / 2
    y = img1.height/2 - text_height / 2
    # fill参数的最后一位为透明度,即100就是透明度
    image_draw.text((x, y), text, font=font, fill=(255, 255, 255,160))
    # rotated
    # 设置文本旋转角度
    angle = 45
    # 中心点
    center = (img1.width / 2, img1.height / 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    text_overlay = cv2.warpAffine(np.array(text_overlay), M, (img1.width, img1.height), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    text_overlay = Image.fromarray(text_overlay)
    # 合成透明图像和背景不透明图像
    img1 = Image.alpha_composite(img1, text_overlay)
    img1 = img1.convert('RGB')
    return img1


if __name__ == "__main__":
    img = rotated_watermark('curry.jpg', "This is my fucking house", 20)
    # img.show()
    img.save("curry_mask.jpg")

 效果图:

原图:curry

文字:“This is my fucking house(这是我的主场)”

效果如下:

 如果觉得合适麻烦大家点赞啦!蟹蟹各位~~

猜你喜欢

转载自blog.csdn.net/panghuzhenbang/article/details/131131504
今日推荐