Python adds oblique transparent text watermark to the picture

The comment is written in the code, and it can be used by directly changing the function parameters. When using it, pay attention to setting the font size, transparency, rotation angle and other information. The default text position is the center of the picture. If you want to change the text position, you can modify it according to the code. 

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")

 Renderings:

Original image: curry

Text: "This is my fucking house"

The effect is as follows:

 If you think it is suitable, please give it a thumbs up! Crabs, everyone~~

Guess you like

Origin blog.csdn.net/panghuzhenbang/article/details/131131504