Posted on

出于无聊,用了半小时写(Copy)了一个给照片自动加水印的脚本。大概功能就是将特定照片在右下角添加时间、尺寸、GPS信息(无人机或者手机有)和版权信息。当然,还不够完善,有空了加上读取目录中所有JPG的功能,以及自适应字体大小的功能。

import os
from PIL import Image
from PIL.ExifTags import TAGS
from PIL import ImageFont
from PIL import ImageDraw
def get_exif_data(fname):
    """Get embedded EXIF data from image file."""
    ret = {}
    try:
        img = Image.open(fname)
        if hasattr( img, '_getexif' ):
            exifinfo = img._getexif()
            if exifinfo != None:
                for tag, value in exifinfo.items():
                    decoded = TAGS.get(tag, tag)
                    ret[decoded] = value
                    size = img.size
    except IOError:
        print('IOERROR ' + fname)
    return ret,size
def addText(fname,text):
    img = Image.open(fname)
    draw = ImageDraw.Draw(img)
    # font = ImageFont.truetype(<font-file>, <font-size>)
    font = ImageFont.truetype("Andale.ttf", 64)
    # draw.text((x, y),"Sample Text",(r,g,b))
    draw.text((img.size[0]-img.size[0]/6,img.size[1]-img.size[1]/10),text,(255,255,255),font=font)
    img.save('sample-out.jpg')
    print('Added text')
if __name__ == '__main__':
    fileName = r'/Users/li-yang/Desktop/DSC04467_1.jpg'
    copyright = 'Photo by YangLi'
    exif,size = get_exif_data(fileName)
    print(exif)
    size = str(size[0]) +'*'+ str(size[1])
    if 'DateTimeOriginal' in exif:
        time = exif['DateTimeOriginal']
    else:
        time= 'No Time Info'
    if 'Model' in exif:
        model = exif['Model']
    else:
        model = 'No Model Info'
    if 'GPSInfo' in exif:
        GPS = exif['GPSInfo']
    else:
        GPS = 'No GPS Info'
    text = time +'\n' + size +'\n' +GPS+'\n' +copyright
    addText(fileName,text)

发表回复