Python+PIL 圖片自動打水印

該程序的功能是,批量給圖片打水印,水印居中顯示,默認透明度50%

廢話不多說直接上代碼

from PIL import Image
import os

# 圖片輸入路徑
input_dir = 'img\\'
# 圖片輸出路徑
output_dir = 'res\\'
# 水印文件
watermark_file = 's.png'
# 水印透明度
transparency = 0.5
# 水印和圖片的比例
watermark_scale = 2

if not os.path.isdir(input_dir):
    print('當前目錄沒有找到輸入文件夾:img\\')
    exit()
if not os.path.isdir(output_dir):
    os.mkdir(output_dir)
if not os.path.exists(watermark_file):
    print('當前目錄沒有找到水印文件:s.png')

def add_watermark(img_file):
    global input_dir
    global output_dir
    global watermark_file
    global transparency
    global watermark_scale

    file_ex = os.path.splitext(img_file)[1].lower()
    if file_ex!='.jpg' and file_ex!='.bmp' and file_ex!='.jpeg' and file_ex!='.png':
        print("不支持",img_file,"文件格式,只支持jpg bmp jpeg png")
        return

    print("正在處理", img_file)
    img_file_path = os.path.join(input_dir, img_file)
    img = Image.open(img_file_path)
    img_w, img_h = img.size

    watermark_img = Image.open(watermark_file)
    watermark_w, watermark_h = watermark_img.size
    if watermark_w*watermark_scale>img_w or watermark_h*watermark_scale>img_h:
        resize_scale = 1
        if img_h/watermark_h>img_w/watermark_w:
            resize_scale=watermark_w/(img_w/watermark_scale)
        else:
            resize_scale=watermark_h/(img_h/watermark_scale)
        dst_w = int(watermark_w//resize_scale)
        dst_h = int(watermark_h//resize_scale)
        watermark_img = watermark_img.resize((dst_w,dst_h))
        watermark_h, watermark_w = dst_h, dst_w

    pos_y = (img_h - watermark_h)//2
    pos_x = (img_w - watermark_w)//2
    watermark_overlay = Image.new('RGBA', img.size, (255, 255, 255, 0))
    watermark_overlay.paste(watermark_img,(pos_x,pos_y))
    # 設置每個像素點顏色的透明度
    for x in range(watermark_overlay.size[0]):
        for y in range(watermark_overlay.size[1]):
            color = watermark_overlay.getpixel((x, y))
            if color[3]>0:
                color = (color[0],color[1],color[2],int(color[3]*transparency))
                watermark_overlay.putpixel((x, y), color)
    rgba_image = img.convert('RGBA')
    res_img = Image.alpha_composite(rgba_image, watermark_overlay)
    output_file = os.path.join(output_dir, img_file)
    if file_ex!='.png':
        res_img = res_img.convert('RGB')
    res_img.save(output_file)

for img_file in os.listdir(input_dir):
    add_watermark(img_file)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章