exif的使用

最近在使用python3操作exif的相关信息,找了相关的exif信息的写入,终于能满足自己的需求,在这里记录一下查询的结果。

exif的tag标签和属性:
http://exiv2.org/tags.html

pyexiv2是python2版本,window和linux都可用(资料相对较多,可以自行查找):
pyexiv2相关参考网址:
https://www.cnblogs.com/lijia168/p/6693862.html

python2和python3版本的都有,linux比较适用,没有可直接使用的window的安装包,需要借助其他软件进行编译,才能使用,如果是linux用户,可以使用比较方便。
gexiv2相关参考网址:
https://wiki.gnome.org/action/show/Projects/gexiv2?action=show&redirect=gexiv2
https://lazka.github.io/pgi-docs/#GExiv2-0.10

py3exiv2是根据pyexiv2的python2版本转化为python3版本,linux比较适用,没有可直接使用的window的安装包,需要借助其他软件进行编译,才能使用,如果是linux用户,可以使用比较方便。
py3exiv2相关参考网址:
https://github.com/mcmclx/py3exiv2
https://python3-exiv2.readthedocs.io/en/latest/developers.html
https://pypi.org/project/py3exiv2/
http://www.py3exiv2.tuxfamily.org/

piexif是python3版本,建议使用pyexiv2,操作相对简单,但是相关教程比较少,可使用window和linux版本。
piexif相关参考网址:
https://pypi.org/project/piexif/#description
https://piexifjs.readthedocs.io/en/latest/index.html      piexif的技术文档      
https://blog.csdn.net/cracker_zhou/article/details/51345649       参考
https://shkspr.mobi/blog/2017/11/adjusting-timestamps-on-images-with-python/     调整时间参数数https://programtalk.com/python-examples/piexif./          piexif的函数的相关demo
https://gist.github.com/c060604/8a51f8999be12fc2be498e9ca56adc72     GPS信息(代码在下面)
https://gist.github.com/NeoFarz/27f35ec2f84f5c52394cea3891c18832     时间信息(代码在下面)

备注:有些网站需要梯子,将相关网址复制到浏览器可进行查阅

读取exif信息并调整时间:

#! python3
# photoDateTime.py - Adds DateTime to images without EXIF DateTimeOriginal

import os, datetime, shutil, sys

try :
  import piexif
except ImportError:  
  exit("This script requires piexif.\nInstall with pip3 install piexif")

def get_datetime(dateFormat, f) :
  epoch_s = input('Enter DateTime (YYYY:MM:DD HH:MM:SS) for ' + f + ': ')
  try :
    epoch_t = datetime.datetime.strptime(epoch_s, dateFormat)
  except ValueError:
    exit('INVALID INPUT: \'' + epoch_s + '\' must but in ' + dateFormat + ' format')
  return(epoch_t.strftime(dateFormat).encode())

def main(argv) :
  dateFormat = '%Y:%m:%d %H:%M:%S'
  dir = sys.argv[1]
  suff = sys.argv[2]
  os.chdir(dir)
  srclist = os.listdir('.')
  
  for f in srclist :
    fUpper = f.upper()
    if (suff in fUpper) :
      ftags = piexif.load(f)
      if not piexif.ExifIFD.DateTimeDigitized in ftags['Exif']:
        epoch = get_datetime(dateFormat, f)
        ftags['Exif'][piexif.ExifIFD.DateTimeOriginal] = epoch
        ftags['Exif'][piexif.ExifIFD.DateTimeDigitized] = epoch
      elif not piexif.ExifIFD.DateTimeOriginal in ftags['Exif']:
        ftags['Exif'][piexif.ExifIFD.DateTimeOriginal] = tags['Exif'][piexif.ExifIFD.DateTimeDigitized]
      else :
        print(f + ' already has a DataTimeOriginal value: ' + ftags['Exif'][piexif.ExifIFD.DateTimeOriginal].decode('utf-8'))
        continue
      piexif.insert(piexif.dump(ftags), f)
      print(f + ' has an updated DateTime of: ' + epoch.decode('utf-8'))
      
    else :
      continue
  
  pass

if __name__ == "__main__":
    main(sys.argv)

读取exif信息写入GPS信息:

import os
import piexif
from fractions import Fraction

def to_deg(value, loc):
    """convert decimal coordinates into degrees, munutes and seconds tuple
    Keyword arguments: value is float gps-value, loc is direction list ["S", "N"] or ["W", "E"]
    return: tuple like (25, 13, 48.343 ,'N')
    """
    if value < 0:
        loc_value = loc[0]
    elif value > 0:
        loc_value = loc[1]
    else:
        loc_value = ""
    abs_value = abs(value)
    deg =  int(abs_value)
    t1 = (abs_value-deg)*60
    min = int(t1)
    sec = round((t1 - min)* 60, 5)
    return (deg, min, sec, loc_value)


def change_to_rational(number):
    """convert a number to rantional
    Keyword arguments: number
    return: tuple like (1, 2), (numerator, denominator)
    """
    f = Fraction(str(number))
    return (f.numerator, f.denominator)


def set_gps_location(file_name, lat, lng, altitude):
    """Adds GPS position as EXIF metadata
    Keyword arguments:
    file_name -- image file
    lat -- latitude (as float)
    lng -- longitude (as float)
    altitude -- altitude (as float)
    """
    lat_deg = to_deg(lat, ["S", "N"])
    lng_deg = to_deg(lng, ["W", "E"])

    exiv_lat = (change_to_rational(lat_deg[0]), change_to_rational(lat_deg[1]), change_to_rational(lat_deg[2]))
    exiv_lng = (change_to_rational(lng_deg[0]), change_to_rational(lng_deg[1]), change_to_rational(lng_deg[2]))

    gps_ifd = {
        piexif.GPSIFD.GPSVersionID: (2, 0, 0, 0),
        piexif.GPSIFD.GPSAltitudeRef: 1,
        piexif.GPSIFD.GPSAltitude: change_to_rational(round(altitude)),
        piexif.GPSIFD.GPSLatitudeRef: lat_deg[3],
        piexif.GPSIFD.GPSLatitude: exiv_lat,
        piexif.GPSIFD.GPSLongitudeRef: lng_deg[3],
        piexif.GPSIFD.GPSLongitude: exiv_lng,
    }

    exif_dict = {"GPS": gps_ifd}
    exif_bytes = piexif.dump(exif_dict)
    piexif.insert(exif_bytes, file_name)

猜你喜欢

转载自blog.csdn.net/qq_22169787/article/details/88787906