如何在python中的图像上设置水印文本

Jes*_*ica 1 python python-imaging-library

我想在图像上设置水印文本...所以我尝试使用 PIL 库

def watermark_text(input_image,
                   output_image,
                   text, pos):
    photo = Image.open(input_image)
    drawing = ImageDraw.Draw(photo)

    color = (255, 180, 80)
    font = ImageFont.truetype("arial.ttf", 40)
    drawing.text(pos, text, fill=color, font=font)
    photo.show()
    photo.save(output_image)

if __name__ == '__main__':
    img = 'cat.jpg'
    watermark_text(img, 'cats.jpg',
                   text='Sample Location Text',
                   pos=(180, 200))
Run Code Online (Sandbox Code Playgroud)

但我想要这种类型的十字和透明颜色的文本:

Sum*_*Rao 5

以下是如何使半透明水印出现您要求的颜色:

from PIL import Image, ImageDraw, ImageFont
base = Image.open('cats.jpg').convert('RGBA')
width, height = base.size

# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))

# get a font
fnt = ImageFont.truetype('arial.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)

x = width/2
y = height/2

# draw text, half opacity
d.text((x,y), "Hello", font=fnt, fill=(255,255,255,128))
txt = txt.rotate(45)

out = Image.alpha_composite(base, txt)
out.show()
Run Code Online (Sandbox Code Playgroud)