Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

One, foreword

Now stealing is very common things, many people in the use of pictures will not mark the source of the picture or mention the author, this time the watermark is a very good thing. We can watermark images and share them, so that other people can know about the author of the image. Today we will take you to realize the addition of watermark.

Second, text watermarking

When adding watermarks, we are more commonly used is text watermarks. Like @Zacksock, @Juejin :ZackSock, etc. Adding the watermark is very simple, just using the operation to add text to the Pillow module, as follows:

from PIL import Image, ImageFont, ImageDraw
# load font
font = ImageFont.truetype('msyh.ttc'.60)
# loading images
im = Image.open('im.jpg')
# create brush
drawer = ImageDraw.Draw(im)
# Prepare text
text = '@ZackSock'
# draw text
drawer.text((0.0), text, (0.255.0), font)
im.show()
Copy the code

There are a few things to pay attention to, the first being the size of the watermark. The watermark size is also the text size, which is determined by:

font = ImageFont.truetype('msyh.ttc'.60)
Copy the code

, so we can adjust the watermark size by adjusting this parameter. The second point is the watermark position and watermark color, this is through:

drawer.text((0.0), text, (0.255.0), font)
Copy the code

Where (0,0) represents the coordinates of the upper left corner of the watermark, and (0,255,0) represents the RGB value of the watermark. For specific adjustment, please refer to the RGB color table.

3. Image watermarking

Text watermarking is convenient to use, but sometimes we prefer to use representative logo as watermarking, then we can use image watermarking, the code is as follows:

from PIL import Image
im = Image.open('origin.png')
watermark = Image.open('watermark.png')
w, h = im.size
watermark.thumbnail((w//6, h//6))
# get watermark size
w2, h2 = watermark.size
# calculate position
x = w-w2
y = h-h2
# paste
im.paste(watermark, (x, y))
im.show()
Copy the code

The implementation effect is as follows:This is basically callingpasteMethod, which is used to paste images. We adjust the size of the watermark and paste it on the original picture. In addition, if the transparent image is used as the watermark, there is a problem with the above code, we can modify it as follows:

from PIL import Image
im = Image.open('origin.png').convert('RGBA')
watermark = Image.open('watermark.png').convert('RGBA')
w, h = im.size
watermark.thumbnail((w//6, h//6))
# Get the transparent layer of watermark
r, g, b, a = watermark.split()
w2, h2 = watermark.size
x = w-w2
y = h-h2
# Let transparent images paste normally
im.paste(watermark, (x, y), mask=a)
im.show()
Copy the code

After our modification, the transparent picture can be pasted normally.