Python 使用 PIL 从 EXIF 数据中获取照片的拍摄日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23064549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:12:18  来源:igfitidea点击:

Get date and time when photo was taken from EXIF data using PIL

pythonpython-imaging-libraryexif

提问by sashoalm

I can get the EXIF data from an imageusing PIL, but how can I get the date and time that the photo was taken?

我可以使用 PIL从图像中获取 EXIF 数据,但是如何获取照片的拍摄日期和时间?

采纳答案by sashoalm

Found the answer eventually, the tag I needed was 36867:

最终找到了答案,我需要的标签是36867

from PIL import Image
def get_date_taken(path):
    return Image.open(path)._getexif()[36867]

回答by tpatja

From the dict returned by _getexif() using key 'DateTimeOriginal'?

从 _getexif() 使用键“DateTimeOriginal”返回的字典?

回答by Alecz

I like to use exif-pybecause it's pure-python, does not require compilation/installation, and works with both python 2.x and 3.x making it ideal for bundling with small portable python applications.

我喜欢使用,exif-py因为它是纯 python,不需要编译/安装,并且可以与 python 2.x 和 3.x 一起使用,使其非常适合与小型便携式 python 应用程序捆绑。

Link: https://github.com/ianare/exif-py

链接:https: //github.com/ianare/exif-py

Example to get the date and time a photo was taken:

获取照片拍摄日期和时间的示例:

import exifread
with open('image.jpg', 'rb') as fh:
    tags = exifread.process_file(fh, stop_tag="EXIF DateTimeOriginal")
    dateTaken = tags["EXIF DateTimeOriginal"]
    return dateTaken

回答by Kirill Vladi

try:
    import PIL
    import PIL.Image as PILimage
    from PIL import ImageDraw, ImageFont, ImageEnhance
    from PIL.ExifTags import TAGS, GPSTAGS
except ImportError as err:
    exit(err)


class Worker(object):
    def __init__(self, img):
        self.img = img
        self.get_exif_data()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    def get_exif_data(self):
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        self.exif_data = exif_data
        # return exif_data 

    def get_date_time(self):
        if 'DateTime' in self.exif_data:
            date_and_time = self.exif_data['DateTime']
            return date_and_time 


def main():
    date = image.date
    print(date)

if __name__ == '__main__':
    try:
        img = PILimage.open(path + filename)
        image = Worker(img)
        date = image.date
        print(date)

    except Exception as e:
        print(e)

回答by getup8

This has changed slightly in more recent versions of Pillow (6.0+ I believe).

这在最近版本的 Pillow(我相信 6.0+)中略有改变。

They added a public method getexif()that you should use. The previous version was private and experimental (_getexif()).

他们添加了一个getexif()您应该使用的公共方法。以前的版本是私有的和实验性的 ( _getexif())。

from PIL import Image

im = Image.open('path/to/image.jpg')
exif = im.getexif()
creation_time = exif.get(36867)

回答by Jason

ExifTags.TAGSis a mapping from tag to tag name. You can use it to create a map of tag names to values.

ExifTags.TAGS是从标签到标签名称的映射。您可以使用它来创建标记名称到值的映射。

On this particular picture, there are a few different "date" properties (DateTime, DateTimeOriginal, DateTimeDigitized) that could be used.

在这张特定的图片上,可以使用一些不同的“日期”属性(DateTimeDateTimeOriginalDateTimeDigitized)。

import json
from PIL import Image, ExifTags
from datetime import datetime

def main(filename):
    image_exif = Image.open(filename)._getexif()
    if image_exif:
        # Make a map with tag names
        exif = { ExifTags.TAGS[k]: v for k, v in image_exif.items() if k in ExifTags.TAGS and type(v) is not bytes }
        print(json.dumps(exif, indent=4))
        # Grab the date
        date_obj = datetime.strptime(exif['DateTimeOriginal'], '%Y:%m:%d %H:%M:%S')
        print(date_obj)
    else:
        print('Unable to get date from exif for %s' % filename)

Output:

输出:

{
    "DateTimeOriginal": "2008:11:15 19:36:24",
    "DateTimeDigitized": "2008:11:15 19:36:24",
    "ColorSpace": 1,
    "ExifImageWidth": 3088,
    "SceneCaptureType": 0,
    "ExifImageHeight": 2320,
    "SubjectDistanceRange": 2,
    "ImageDescription": "               ",
    "Make": "Hewlett-Packard                ",
    "Model": "HP Photosmart R740             ",
    "Orientation": 1,
    "DateTime": "2008:11:15 19:36:24",
    ...
}
2008-11-15 19:36:24