Member-only story

[Python] How to get EXIF from a file

Jack in the world
10 min readSep 19, 2019

--

目標

  1. 開啟檔案
  2. 取得EXIF的Date Time等資料
  3. 把檔案名稱根據EXIF的時間日期更改成固定格式

取得EXIF

在網上找了一下,決定使用PIL這個package. 這是個外加的package,所以需要另外安裝

pip install Pillow

開啟檔案以及取得EXIF的資料,用以下範例碼可以做到

from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
def process_file():
# open the file
i_file = Image.open('P2019_0917_17384450.jpg') # test file
# Get EXIF
exif_info = i_file._getexif()
for tag, val in exif_info.items():
key = TAGS.get(tag)
     # GPSInfo has sub-level of data
if key == "GPSInfo":
for t in val:
sub_decoded = GPSTAGS.get(t, t)
print(f'[{tag}] {sub_decoded}: {val[t]}')
print(f'[{tag}] {key}: {val}')
if __name__ == '__main__':
process_file()

取得DateTime以及轉換

從EXIF tags可以取得數個不同的Datetime,至少可以取得兩個參數:

  • DateTimeOriginal
  • DateTimeDigitized

這裡我取用DateTimeDigitized這一個參數,它的格式如下:

2019:09:17 17:38:44
# yyyy:mm:dd hh:mm:ss

GPS裡面有兩個參數跟時間有關:

  • GPSDateStamp
  • GPSTimeStamp

GPSTimeStamp很麻煩,因為它的格式是turple而不是單純的integer.所以必須先轉換成integer然後再當成timestamp轉換成時間

GPSTimeStamp: ((21, 1), (38, 1)

--

--

Jack in the world
Jack in the world

Written by Jack in the world

Where in the world is Jack? 在這個世界上, 我們都在找尋自己的所在. 寫程式是我的嗜好和工作, 好好地生活在這個世界是我的日常, 學習新知識是我的快樂.

No responses yet