wartermark your image

lazymonkey posted @ 2012年5月21日 18:58 in 语言与设计 with tags 图像处理 python , 5354 阅读

《Windows网络程序设计》考试在几天前就结束了,第一次在试卷上写代码写到手痛,只能说考试很水很恶心!最近翻了一下zsh的文档,突然想自己写一个shell来玩一下,结果写了一点基本的东西(只完成了执行进程和信号控制)就写不下去了,总想着添加接口的问题,于是又去看lua(已是第二次!)、翻云风大神的Blog(很多都是看不懂的),决定还是应该深入了解一下lua。这些都是题外话,与主题无关!wheel...在这里图片在blog中是没有水印的,今天特意用python的PIL模块写了一个简陋的添加水印的脚本。PIL模块在很久之前就用过了,不过当时是拿来生成验证码,;-D。。。对于简单的图像处理来说,PIL足以应付了(虽然我更喜欢opencv ;)),只能感叹一下python的模块真的很管用!

PIL生成水印图像很简单,把你的水印添加到源图像来生成目标图像,一个简单例子:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import Image

source_img = Image.open('source.png')
logo_img = Image.open('logo.png')   # 要保证你的logo是透明的哟。。。废话!
source_img.paste(logo_img, (source_img.size[0] - logo_img.size[0],
                 source_img.size[1] - logo_img.size[1]), logo_img)
source_img.save('target.png', 'PNG')

看看效果:

这是源图像:

要添加的logo:

添加图像水印后:

还不错,继续pythonic,添加文字水印,也比较简单:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont

TEXT_FONT = "/home/lazymonkey/.fonts/Fabada-regular.ttf"     # 规定所使用的字体
FONT_SIZE = 14                                               # 设置14号字体
img       = Image.open('source.png')
text      = 'Hello world!'

watermark = Image.new("RGBA", (img.size[0], img.size[1]))
draw      = ImageDraw.ImageDraw(watermark, "RGBA")
font      = ImageFont.truetype(TEXT_FONT, FONT_SIZE)
draw.setfont(font)
draw.text((480, 560), text, 'Red')
img.paste(watermark, None, watermark)
img.save('target.png', 'PNG')

看看效果:

ok,封装一下:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''

#                 {/ . .\}
#                 ( (oo)   )
#+--------------oOOo---︶︶︶︶---oOOo------------------+
#     FileName  :           wartermark.py
#     Describe  :           take wartermark to your image
#     Author    :           Lazy.monkey™
#     Email     :           lazymonkey.me@gmail.com
#     HomePage  :           lazymonkey.is-programmer.com
#     Version   :           0.0.1
#     LastChange:           2012-05-21 15:57:55
#+------------------------------------Oooo--------------+


'''
'''
Notes : 0. 请设定输出为png图片格式,以得到最佳效果
        1. 请设定字体为你系统内的字体
Usages: 0. python watermark.py source_img -l 'yourlogo' target_img
        1. python watermark.py source_img -t 'text you want' target_img
'''
from PIL import Image, ImageDraw, ImageFont
from math import atan, degrees
import sys
import os

TEXT_FONT = "/home/lazymonkey/.fonts/Fabada-regular.ttf"     # 规定所使用的字体
ALPHA     = True

def usage():
    if len(sys.argv) != 5:
        sys.exit("Usage: %s <options> <intput-image <text or logo> <output-image>"
                % os.path.basename(sys.argv[0]))

def logo4mark(filename, logo, outfilename):
    img      = Image.open(filename)
    logo_img = Image.open(logo)   # 要保证你的logo是透明的哟。。。废话!

    img.paste(logo_img, (img.size[0] - logo_img.size[0],
              img.size[1] - logo_img.size[1]), logo_img)
    img.save(outfilename)

def text4mark(filename, text, outfilename):
    img       = Image.open(filename).convert("RGB")
    watermark = Image.new("RGBA", (img.size[0], img.size[1]))
    draw      = ImageDraw.ImageDraw(watermark, "RGBA")
    font_size = 0
    ##
    # @brief 得到最佳字体大小
    while True:
        font_size += 1
        nextfont = ImageFont.truetype(TEXT_FONT, font_size)
        nexttextwidth, nexttextheight = nextfont.getsize(text)
        if nexttextwidth+nexttextheight/3 > watermark.size[0]:
            break
        font = nextfont
        textwidth, textheight = nexttextwidth, nexttextheight

    draw.setfont(font)
    draw.text(((watermark.size[0]-textwidth)/2,
               (watermark.size[1]-textheight)/2), text)
    watermark = watermark.rotate(degrees(atan(float(img.size[1])/
                                              img.size[0])),
                                 Image.BICUBIC)
    if ALPHA is True:   # 水印透明
        mask = watermark.convert("L").point(lambda x: min(x, 55))
    watermark.putalpha(mask)
    img.paste(watermark, None, watermark)
    img.save(outfilename)

if __name__ == "__main__":
    usage()
    if sys.argv[1] == '-l':
        logo4mark(*sys.argv[2:])
    if sys.argv[1] == '-t':
        text4mark(*sys.argv[2:])

看看透明文字水印的效果:

 

  • 无匹配
Avatar_small
依云 说:
2012年5月21日 19:23

为什么不试试 ImageMagick 呢?一行命令就能够解决哦亲~

Avatar_small
lazymonkey 说:
2012年5月21日 20:27

@依云: 果然,你赢了。。。我这是没事瞎折腾啊!重复造轮子咯。。。:(

Avatar_small
依云 说:
2012年5月21日 20:38

@lazymonkey: 喂,你就再去折腾下 ImageMagick 嘛,然后把最终的命令贴出来 ^_^

Avatar_small
lazymonkey 说:
2012年5月21日 20:47

@依云: 呃。。。ImageMagick做水印已经有人写了,我没机会啊!:-D http://tuxtweaks.com/2009/08/howto-watermark-images-imagemagick-linux/

Avatar_small
依云 说:
2012年5月21日 21:24

@lazymonkey: Thanks! 有时间研究下。

seo service UK 说:
2024年1月16日 18:12

Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates.

먹튀폴리스신고 说:
2024年2月11日 13:57

“I have to say, your blog is a breath of fresh air. There are so many generic and uninspired blogs out there, but yours really stands out for its originality and creativity.”

카지노탐구생활 说:
2024年2月11日 14:19

Hello, you used to write excellent, but the last few posts have been kinda boring? I miss your tremendous writings. Past several posts are just a little out of track! come on!

토크리 说:
2024年2月11日 14:34

I was suggested this web site through my cousin. I’m not certain whether this put up is written through him as no one else recognize such exact approximately my difficulty. You’re wonderful! Thank you!

토토읕 说:
2024年2月11日 14:43

I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Great work!

토토사이트순위 说:
2024年2月11日 14:49

We’re a group of volunteers and starting a new scheme in our community. Your website provided us with valuable information to work on. You’ve done a formidable job and our entire community will be grateful to you.

안전놀이터검증 说:
2024年2月11日 14:56

Great work! That is the kind of info that should be shared across the internet. Shame on Google for now not positioning this submit upper! Come on over and visit my web site . Thanks =)

ok토토먹튀검증 说:
2024年2月11日 15:01

Great work! That is the kind of info that should be shared across the internet. Shame on Google for now not positioning this submit upper! Come on over and visit my web site . Thanks =)

토토사이트 说:
2024年2月11日 15:06

Thank you for every other magnificent article. Where else may just anyone get that kind of info in such an ideal manner of writing? I have a presentation subsequent week, and I am at the search for such info.

먹튀폴리스 说:
2024年2月11日 15:14

My spouse and I absolutely love your blog and find a lot of your post’s to be exactly what I’m looking for. Do you offer guest writers to write content in your case? I wouldn’t mind writing a post or elaborating on a few of the subjects you write with regards to here. Again, awesome web site!

메이저놀이터 说:
2024年2月11日 15:24

“I have to say, your blog is a breath of fresh air. There are so many generic and uninspired blogs out there, but yours really stands out for its originality and creativity.”

먹튀검증 说:
2024年2月11日 15:31

I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back down the road. Cheers

메이저사이트 说:
2024年2月11日 15:36

I was suggested this web site through my cousin. I’m not certain whether this put up is written through him as no one else recognize such exact approximately my difficulty. You’re wonderful! Thank you!

사설토토 说:
2024年2月11日 15:47

I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Great work!

토토사이트검증 说:
2024年2月11日 15:53

It is really a nice and helpful piece of info. I?m glad that you shared this useful information with us. Please keep us informed like this. Thanks for sharing.

메이저사이트 说:
2024年2月11日 16:07

Oh my goodness! an amazing article dude. Thank you Nevertheless I am experiencing situation with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting identical rss downside? Anybody who is aware of kindly respond. Thnkx

온라인카지노순위 说:
2024年2月11日 16:37

Hi, i feel that i noticed you visited my website so i got here to ?go back the prefer?.I’m trying to to find things to enhance my website!I guess its ok to use some of your ideas!!

카지노사이트목록 说:
2024年2月11日 16:42

Thank you for every other magnificent article. Where else may just anyone get that kind of info in such an ideal manner of writing? I have a presentation subsequent week, and I am at the search for such info.

메이저토토사이트 说:
2024年2月11日 16:48

My spouse and I absolutely love your blog and find a lot of your post’s to be exactly what I’m looking for. Do you offer guest writers to write content in your case? I wouldn’t mind writing a post or elaborating on a few of the subjects you write with regards to here. Again, awesome web site!

วิธีใช้งานคาสิโนออนไ 说:
2024年2月11日 16:56

This may be the proper weblog for desires to find out about this topic. You know so much its virtually challenging to argue along (not too I really would want…HaHa). You definitely put a new spin for a topic thats been revealed for some time. Excellent stuff, just great!

먹튀검증업체 说:
2024年2月11日 17:04

Thanks, I have all the files, is there any way that the geometry and mesh can be connected again? Now, I can import to a new .wbpj each file independently, so if I need to remesh my model, I need to change the geometry and start meshing from scratch.

안전토토사이트 说:
2024年2月11日 17:14

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

먹튀검증 说:
2024年2月11日 17:18

Goodness! Such an astounding and supportive post this is. I outrageously cherish it. It's so great thus amazing. I am simply flabbergasted. I trust that you keep on doing your work like this later on moreover.

토토사이트추천 说:
2024年2月11日 17:24

Operational Challenges:New Rabbit's continuous address changes may pose inconveniences for users seeking a stable and reliable webtoon experience.

먹튀검증사이트 说:
2024年2月11日 17:54

Impressive web site, Distinguished feedback that I can tackle. Im moving forward and may apply to my current job as a pet sitter, which is very enjoyable, but I need to additional expand. Regards.

먹튀검증사이트 说:
2024年2月11日 18:08

Useful information. Fortunate me I discovered your web site by accident, and I am stunned why this accident didn’t came about in advance! I bookmarked it.

먹튀검증사이트 说:
2024年2月11日 18:09

Useful information. Fortunate me I discovered your web site by accident, and I am stunned why this accident didn’t came about in advance! I bookmarked it.

먹튀검증사이트 说:
2024年2月11日 18:46

I truly contented to come all over your special data. I like this web page.

먹튀검증 说:
2024年2月11日 18:51

Two full thumbs up for this magneficent article of yours. I've truly delighted in perusing this article today and I figure this may be outstanding amongst other article that I've perused yet. If it's not too much trouble keep this work going ahead in a similar quality.

메리트카지노 说:
2024年2月11日 18:56

Thanks for sharing this interesting blog with us.My pleasure to being here on your blog..I wanna come beck here for new post from your site 

토토사이트순위 说:
2024年2月11日 19:06

I discovered your this post while hunting down some related data on website search...Its a decent post..keep posting and upgrade the data 

메이저놀이터순위 说:
2024年2月11日 19:12

“I have to say, your blog is a breath of fresh air. There are so many generic and uninspired blogs out there, but yours really stands out for its originality and creativity.”

토토검증사이트 说:
2024年2月11日 19:18

I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back down the road. Cheers

안전토토사이트 说:
2024年2月11日 19:24

I was suggested this web site through my cousin. I’m not certain whether this put up is written through him as no one else recognize such exact approximately my difficulty. You’re wonderful! Thank you!

메이저토토사이트 说:
2024年2月11日 19:43

I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme? Great work!

먹튀검증사이트 说:
2024年2月11日 19:50

It is really a nice and helpful piece of info. I?m glad that you shared this useful information with us. Please keep us informed like this. Thanks for sharing.

먹튀검증커뮤니티 说:
2024年2月11日 19:57

Oh my goodness! an amazing article dude. Thank you Nevertheless I am experiencing situation with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting identical rss downside? Anybody who is aware of kindly respond. Thnkx


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter