= 0 and opacity "/> = 0 and opacity ">

首页  >  文章  >  后端开发  >  python使用PIL制作水印

python使用PIL制作水印

巴扎黑
巴扎黑原创
2016-12-08 10:50:251576浏览

import Image, ImageEnhance
 
def reduce_opacity(im, opacity):
    """Returns an image with reduced opacity."""
    assert opacity >= 0 and opacity <= 1
    if im.mode != &#39;RGBA&#39;:
        im = im.convert(&#39;RGBA&#39;)
    else:
        im = im.copy()
    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)
    return im
 
def watermark(im, mark, position, opacity=1):
    """Adds a watermark to an image."""
    if opacity < 1:
        mark = reduce_opacity(mark, opacity)
    if im.mode != &#39;RGBA&#39;:
        im = im.convert(&#39;RGBA&#39;)
    # create a transparent layer the size of the image and draw the
    # watermark in that layer.
    layer = Image.new(&#39;RGBA&#39;, im.size, (0,0,0,0))
    if position == &#39;tile&#39;:
        for y in range(0, im.size[1], mark.size[1]):
            for x in range(0, im.size[0], mark.size[0]):
                layer.paste(mark, (x, y))
    elif position == &#39;scale&#39;:
        # scale, but preserve the aspect ratio
        ratio = min(
            float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
        w = int(mark.size[0] * ratio)
        h = int(mark.size[1] * ratio)
        mark = mark.resize((w, h))
        layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
    else:
        layer.paste(mark, position)
    # composite the watermark with the layer
    return Image.composite(layer, im, layer)
 
def test():
    im = Image.open(&#39;test.png&#39;)
    mark = Image.open(&#39;overlay.png&#39;)
    watermark(im, mark, &#39;tile&#39;, 0.5).show()
    watermark(im, mark, &#39;scale&#39;, 1.0).show()
    watermark(im, mark, (100, 100), 0.5).show()
 
if __name__ == &#39;__main__&#39;:
    test()

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn