You can set whether to add watermarks when writing articles. However, some pictures may want to be watermarked, some do not want to watermark, how to do?

Configure the environment

python3 + pillow

pip3 install pillowCopy the code

Import library

from PIL import Image, ImageSequence
import os
import randomCopy the code

Effect preview:



Usage:

  1. Add the watermark image logo.png in the same directory as the script
  2. Create the input directory and place the image to be watermarked
  3. Create directory output execute the script addlogo.py
  4. The output is in the Output folder

Realize the principle of

Watermarking image collection:

First read the pixel information and size information of the watermark image. Remove the pixel with transparency 0 and modify the transparency pixel information.

img_logo = Image.open("logo.png") img_logo_width, img_logo_height = img_logo.size img_logo_pixels = dict() for w in range(img_logo_width): for h in range(img_logo_height): c = img_logo.getpixel((w,h)) if c! =(0, 0, 0, 0): img_logo_pixels[(w, h)] = c[:3]+(125,)Copy the code


Blend colors:

Color mix is adopted for each pixel, where C1 is the pixel information of the source image (R, G, B, A) and C2 is the pixel information of the logo image. The hybrid algorithm is as follows:

def blendPixel(c1,c2): A1 = 256 - c2 [3] a2 = c2 [3] - (a1 * c2 [3])/c = a = 256.0 a1 + a2 (int (c1 [0] + a2 (a1 * * c2 [0])/a), int (c1 [1] + a2 (a1 * * c2 [1])/a), int((a1*c1[2] + a2*c2[2])/a),int(a)) return cCopy the code

Process the source Image object:

Start processing pixels at a random location. Refer to the code below.

def dealOneImage(image,offX=None,offY=None): w, h = image.size offX = offX if offX else random.random(); offY = offY if offY else random.random(); If w>=img_logo_width and h>=img_logo_height: top = int((w - img_logo_width)*offX) left = int((h - img_logo_height)*offY) for p, c in img_logo_pixels.items(): p_x = (p[0]+top) p_y = (p[1]+left) image_c = image.getpixel((p_x,p_y)) if(isinstance(image_c, tuple) and len(image_c)>2): image.putpixel((p_x, p_y), blendPixel(image_c,c)) return image;Copy the code

Working with a single file:

For GIF file first split into a picture, add watermark on the picture, and finally synthesize GIF. For other formats of the picture file can add a few more watermarks. Finally, the output is saved to the output folder.

def dealOneFile(filePath):
    img_orign = Image.open(filePath)
    _,file_type = os.path.splitext(filePath)
    basename = os.path.basename(filePath)
    if file_type == '.gif':
        sequence = [];
        offX=random.random()
        offY=random.random()
        for f in ImageSequence.Iterator(img_orign):
            if len(sequence) % 2 == 0:
                offX=random.random()
                offY=random.random()
            sequence.append(dealOneImage(f.convert(),offX,offY))
        sequence[0].save(f'./output/{basename}', save_all=True, append_images=sequence[1:])
    else:
        image_out = (dealOneImage(img_orign))
        for x in range(1):
            image_out = (dealOneImage(image_out))
        image_out.save(f'./output/{basename}')Copy the code

Processing directory:

Do a filter on the files in the current directory, select only files in image format.

def dealSrc(srcDir):
    picFiles = [os.path.join(srcDir,fn) for fn in os.listdir(srcDir) if fn.endswith(('.gif', '.jpg', '.png','.jpeg'))]
    for filePath in picFiles:
        dealOneFile(filePath)Copy the code

summary

Python3’s Pillow library is used to add watermarks. The logo image is read first, then mixed pixels are added at a random location, and finally saved.

Among them, the processing of GIF files is to remove frames, add watermarks, and finally combine into a GIF. This can only correspond to the relatively small GIF file processing, if there is a better way to welcome the message exchange share!

This article is only for personal learning and communication, please do not use it for other purposes!

The resources