python 图片添加日期水印


#! /usr/bin/env python
# -*- coding: utf-8 -*-

# 根据目录从图片提取出日期 并添加图片上
import os
import exifread
from PIL import Image, ImageFont, ImageDraw


def exifread_infos(photo):
    # 加载 ExifRead 第三方库  https://pypi.org/project/ExifRead/
    # 获取照片时间、经纬度信息
    # photo参数:照片文件路径

    # Open image file for reading (binary mode)
    f = open(photo, 'rb')
    # Return Exif tags
    tags = exifread.process_file(f)

    try:
        # 拍摄时间
        EXIF_Date = tags["EXIF DateTimeOriginal"].printable
        # 纬度
        LatRef = tags["GPS GPSLatitudeRef"].printable
        Lat = tags["GPS GPSLatitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
        Lat = float(Lat[0]) + float(Lat[1]) / 60 + float(Lat[2]) / float(Lat[3]) / 3600
        if LatRef != "N":
            Lat = Lat * (-1)
        # 经度
        LonRef = tags["GPS GPSLongitudeRef"].printable
        Lon = tags["GPS GPSLongitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
        Lon = float(Lon[0]) + float(Lon[1]) / 60 + float(Lon[2]) / float(Lon[3]) / 3600
        if LonRef != "E":
            Lon = Lon * (-1)
        f.close()
    except:
        # print("ERROR:请确保照片包含经纬度等EXIF信息。")
        return None
    else:
        return EXIF_Date, Lat, Lon


def addDate(photoPath, str):
    # 打开图片
    im = Image.open(photoPath).convert('RGBA')
    if(len(str)<1): #如果没找到日期直接返回 相当于复制
        return im;
    # 新建一个空白图片,尺寸与打开图片一样
    txt = Image.new('RGBA', im.size, (0, 0, 0, 0))
    # 设置字体
    # fnt = ImageFont.truetype("c:/Windows/Fonts/Tahoma.ttf", size=80)
    fnt = ImageFont.truetype("simsun.ttc", size=100, index=1)
    # 操作新建的空白图片>>将新建的图片添入画板
    d = ImageDraw.Draw(txt)
    # 在新建的图片上添加字体
    d.text((115, txt.size[1] - 180), str, font=fnt, fill=(255, 255, 255, 255))
    # 合并两个图片
    out = Image.alpha_composite(im, txt)
    # out.show()
    return out;


def is_img(x):
    """
    判断是不是图片格式的
    :param x:
    :return:
    """
    import re;
    pattern=re.compile(".jpg|.png|.jpeg")
    _a=pattern.findall(x)
    return len(_a)>0


def getData(photo):
    t = exifread_infos(photo)
    # print(t)
    if (t == None):
        return "";
    return t[0]


def saveTargData(out, tarPath):
    out.save(tarPath, quality=95)


Src_Path = "E:/Cmd"


def main():
    listDir = os.listdir(Src_Path);
    out_ = Src_Path + "/out"
    if (not os.path.exists(out_)):
        os.mkdir(out_)
    for item in listDir:
        _is_img = is_img(item)
        # print(item+" " +str(_is_img))
        if (_is_img):
            src = Src_Path + "/" + item
            out = addDate(src, getData(src))
            png_ = item.split(".")[0] + ".png"
            tarPath = out_ + "/" + png_
            print(tarPath)
            saveTargData(out, tarPath)


if __name__ == '__main__':
    main()


你可能感兴趣的:(python 图片添加日期水印)