色彩时光 | 记录程序员世界的点点滴滴

python图片添加水印


几周之前发表了一篇日志:python图片压缩处理 。今天对上次的代码再升级了下,增加了添加水印的功能能,具体代码如下:


import Image,ImageEnhance

def watermark(imagefile, markfile, sw=0, sh=0, opacity=1):
        """Adds a watermark to an image."""
        #im = Image.open(imagefile)
        im=imagefile
        #mark = Image.open(markfile)
        mark=markfile
        if opacity < 1:
            mark = reduceOpacity(mark, opacity)
        if im.mode != 'RGBA':
            im = im.convert('RGBA')
        # create a transparent layer the size of the image and draw the
        # watermark in that layer.
        layer = Image.new('RGBA', im.size, (0,0,0,0))

        if sw<0: sw = im.size[0] - mark.size[0] + sw
        if sh<0: sh = im.size[1] - mark.size[1] + sh
        position = (sw, sh)
        layer.paste(mark, position)

        # composite the watermark with the layer
        return Image.composite(layer, im, layer)

def reduceOpacity(im, opacity):
        """Returns an image with reduced opacity."""
        assert opacity >= 0 and opacity <= 1
        if im.mode != 'RGBA':
            im = im.convert('RGBA')
        else:
            im = im.copy()
        alpha = im.split()[3]
        alpha =          ImageEnhance.Brightness(alpha).enhance(opacity)
        im.putalpha(alpha)
        return im


您可能也对下面文章感兴趣:

Write a Comment


* Content (required) 10~500s

分类

热门标签

友情链接