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

时间:2018-09-10 03:46:01

标签: python python-imaging-library

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="chart" />

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

2 个答案:

答案 0 :(得分:2)

在这里,您可以使半透明水印显示为您要求的颜色:

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

答案 1 :(得分:0)

您可以尝试如下旋转文本:

import ImageFont, ImageDraw, ImageOps

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)
    angle=txt.rotate(17.5,  expand=1)
    photo.paste(ImageOps.colorize(w, (0,0,0), (255, 180, 80)), (242,60),  w)
    photo.show()
    photo.save(output_image)

您可以通过相应的RGB代码在color变量中使用正确的颜色。