python - 填充特定颜色的矩形内的水印

标签 python python-imaging-library

我想在图片上加水印。但只是一个文本,而是一个填充黑色的矩形,里面有一个白色文本。

目前,我只能输入文字:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw

img = Image.open("in.jpg")

draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
#font = ImageFont.truetype("Arialbd.ttf", 66)
draw.text((width - 510, height-100),"copyright",(209,239,8), font=font)
img.save('out.jpg')

最佳答案

这将在黑色矩形背景上绘制文本:

from PIL import Image, ImageFont, ImageDraw

img = Image.open("in.jpg")
width, height = img.width, img.height

draw = ImageDraw.Draw(img)
font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
x, y = (width - 510, height-100)
# x, y = 10, 10
text = "copyright"
w, h = font.getsize(text)
draw.rectangle((x, y, x + w, y + h), fill='black')
draw.text((x, y), text, fill=(209, 239, 8), font=font)
img.save('out.jpg')

enter image description here

使用 imagemagick,可以制作出更好看的水印

from PIL import Image, ImageFont, ImageDraw

font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
text = "copyright"
size = font.getsize(text)
img = Image.new('RGBA', size=size, color=(0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fill=(209, 239, 8), font=font)
img.save('label.jpg')

然后调用(如果你愿意,可以通过subprocess)

composite -dissolve 25% -gravity south label.jpg in.jpg out.jpg

enter image description here

或者如果你用白色背景制作标签,

composite -compose bumpmap -gravity southeast label.jpg in.jpg out.jpg

enter image description here


要从 Python 脚本中运行这些命令,您可以像这样使用 subprocess:

import subprocess
import shlex

from PIL import Image, ImageFont, ImageDraw

font = ImageFont.truetype(
    "/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf", 66)
text = "copyright"
size = font.getsize(text)
img = Image.new('RGBA', size=size, color='white')
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fill=(209, 239, 8), font=font)
img.save('label.jpg')

cmd = 'composite -compose bumpmap -gravity southeast label.jpg in.jpg out.jpg'
proc = subprocess.Popen(shlex.split(cmd))
proc.communicate()

关于python - 填充特定颜色的矩形内的水印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18869365/

相关文章:

python - Scrapy 创建 XML feed 将内容包装在 "value"标签中

python - Django 和枕头

python - ImageGrab.grab(bbox) 和 Image.getpixel() 一起使用

python - Ajax 调用 DRF api "You cannot access body after reading from request' s 数据流”

python - django taggit防止不同模型之间的重叠标签

python - 需要帮助查找 Python 在启动时运行的脚本

python - 如何在 PIL 中选择与图像边缘相邻的所有黑色像素?

python - 根据 DateTimeField 从数据库中自动删除 Django 对象

python - 从内存发送图像

python - 如何为 tiff 文件添加附加标签