批量给图片添加水印

1 办公痛点

1. 为了维护作者版权,需要给文章中照片添加文字水印
2. 网上虽有添加水印的软件,但几乎都需要付费,且没法按照自己要求定制,像公众号、知乎等添加的文字水印的格式都是固定不可修改的
3. 如果需要批量添加,则更加费事费力

2 Python 批量给图片添加文字水印

一键处理就是爽!
利用Python可以编写个性化自定义的文字水印,而且只需编写一遍,便可永久免费重复使用!

3 代码实现

# 导入包
import os
from PIL import Image, ImageDraw, ImageFont

# image: 图片  text:要添加的文本 font:字体
# 指定的水印文字
text = '@apollo_miracle'
# 指定要使用的字体和大小;
font = ImageFont.truetype('simsun.ttc', 24)


for filename in os.listdir('./input/'):
    # 读取文件
    im_before = Image.open('./input/'+filename)
    
    # 转成RGBA模式
    # RGBA是代表Red(紅色)Green(綠色)Blue(藍色)和Alpha(透明度)。
    rgba_image = im_before.convert('RGBA')
    
    # 创建水印层
    text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
    
    # 开始绘制水印层
    image_draw = ImageDraw.Draw(text_overlay)
    
    # 文字的尺寸大小
    text_size_x, text_size_y = image_draw.textsize(text, font=font)
    # 设置文本文字位置
    text_xy = (rgba_image.size[0] - text_size_x, rgba_image.size[1] - text_size_y)
    # 设置文本颜色和透明度
    image_draw.text(text_xy, text, font=font, fill=(76, 234, 124, 100))

    # 合并两层
    image_with_text = Image.alpha_composite(rgba_image, text_overlay)

    # 打开图片
#     im_before.show()
#     im_after.show()
    # 转成 RGB 才能生成 JPEG 图,RNG才是四通道色彩
    im_after = image_with_text.convert('RGB')
    im_after.save('./output/'+filename)

实现效果:

4 优化代码

4.1 导入相关图片处理模块

import PIL
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

4.2 获取图片完整路径列表

import os
def getfilenames(filepath=''):
    '''
    获取图片完整路径列表
    filepath: 图片所在文件夹路径
    '''
    
    # 初始化文件列表
    filelist_out=[]      
    
    # 遍历filepath下的文件
    for filename in os.listdir(filepath):      ## os.listdir(filepath)用于获取filepath下所有文件的文件名
        fi_d = os.path.join(filepath, filename)    ## 合并为完整路径
        filelist_out.append(fi_d) # 添加到路径列表中
    return filelist_out  # 返回文件完整路径列表

4.3 批量给图片添加文字水印

def textMark(imgpath, outputpath, text, text_position='右上角', text_color='白'):
    '''
    批量给图片添加文字水印
    imgpath:图片所在文件夹路径
    outputpath:文字水印图片存放路径
    text:水印文字
    text_position:文字水印添加的位置:左上角、左下角、右上角、右下角、居中,默认是右下角
    text_color:字体颜色:黑、白、红、黄、蓝,默认是白色
    '''

    # 检查文件夹是否存在
    if not os.path.exists(outputpath):
        # 如果文件夹不存在,则创建它
        os.makedirs(outputpath)
    
    # 获取图片完整路径列表
    filelist = getfilenames(imgpath)
    
    # 批量给图片添加文字水印
    for fullfilename in filelist:
        
        # 下列3行代码用于生成添加水印后的图片路径
        temp = fullfilename.split('\\')     
        softfilename = temp[-1].split('.')[0]
        outputfilename = outputpath + '\\' + softfilename + '.jpg'
        
        # 打开图片
        img = Image.open(fullfilename)
        # 记录图片大小
        imgwidth, imgheight = img.size 
        
        # 画图
        draw = ImageDraw.Draw(img)        
        
        # 设置文字的字体
        text_size = int(imgheight / 20)
        font = ImageFont.truetype('simkai.ttf', text_size)
        
        # 设置水印文字位置
        if text_position == '左上角':
            position=(0,0)
        elif  text_position == '左下角':
            position=(0,imgheight-text_size)
        elif  text_position == '右上角':
            position=(imgwidth - text_size*len(text),0)
        elif  text_position == '右下角':
            position=(imgwidth - text_size*len(text), imgheight - text_size)
        elif  text_position == '居中':
            position=(imgwidth/2,imgheight/2)

        # 设置文字颜色
        if text_color == '黑':
            color = '#000000'
        elif text_color == '白':
            color = '#FFFFFF'
        elif text_color == '红':
            color = '#FF0000'
        elif text_color == '黄':
            color == '#FFFF00'
        elif text_color == '蓝':
            color = '#0000FF'
        else:
            print("目前仅支持:黑、白、红、黄、蓝,请输入正确的颜色!")

        # 设置文字格式
        draw.text(position, text, color, font)    
        # 将文字添加到图片上
        draw = ImageDraw.Draw(img)    
        # 转成 RGB 才能生成 JPEG 图,RNG才是四通道色彩
        img = img.convert('RGB')
        #另存图片
        img.save(outputfilename)

4.4 测试

input文件夹用于存放原照片
output文件夹用于存放添加文字水印后的照片

imgpath = './input'
outputpath = './output/右上角'
text = '@apollo_miracle'
textMark(imgpath,outputpath,text, text_position='右上角')

 5 进阶:图片水印

from PIL import Image, ImageDraw
 
def add_watermark_to_image(image, watermark):
    rgba_image = image.convert('RGBA')
    rgba_watermark = watermark.convert('RGBA')

    image_x, image_y = rgba_image.size
    watermark_x, watermark_y = rgba_watermark.size

    # 缩放图片
    scale = 5
    watermark_scale = max(image_x / (scale * watermark_x), image_y / (scale * watermark_y))
    new_size = (int(watermark_x * watermark_scale), int(watermark_y * watermark_scale))
    rgba_watermark = rgba_watermark.resize(new_size, resample=Image.ANTIALIAS)
    # 透明度
    rgba_watermark_mask = rgba_watermark.convert("L").point(lambda x: min(x, 180))
    rgba_watermark.putalpha(rgba_watermark_mask)

    watermark_x, watermark_y = rgba_watermark.size
    # 水印位置
    rgba_image.paste(rgba_watermark, (image_x - watermark_x, image_y - watermark_y), rgba_watermark_mask)

    return rgba_image
 
im_before = Image.open("123.jpg")
# im_before.show()
 
im_watermark = Image.open("watermark.jpg")
im_after = add_watermark_to_image(im_before, im_watermark)
# im_after.show()

# 转成 RGB 才能生成 JPEG 图,RNG才是四通道色彩
im_after = im_after.convert('RGB')
im_after.save('im_after.jpg')

实现效果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值