首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >填充一定颜色的矩形内的水印。

填充一定颜色的矩形内的水印。
EN

Stack Overflow用户
提问于 2013-09-18 10:07:29
回答 1查看 8.2K关注 0票数 6

我想在图片上加一个水印。但只是一个文本,但一个长方形充满了黑色和白色的文本在里面。

现在,我只能写一段文字:

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-18 10:26:38

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

代码语言:javascript
复制
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')

使用imagemagick,可以使用更好的水印

代码语言:javascript
复制
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 )

代码语言:javascript
复制
composite -dissolve 25% -gravity south label.jpg in.jpg out.jpg

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

代码语言:javascript
复制
composite -compose bumpmap -gravity southeast label.jpg in.jpg out.jpg

要在Python脚本中运行这些命令,您可以使用subprocess,如下所示:

代码语言:javascript
复制
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()
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18869365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档