Home >Backend Development >Python Tutorial >Python uses PIL to create watermarks

Python uses PIL to create watermarks

巴扎黑
巴扎黑Original
2016-12-08 10:50:251616browse

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()

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn