Python 取得圖片Exif資訊

本篇 ShengYu 將介紹如何使用 Python 讀取圖片的 Exif 資訊,在做圖片處理時常常會需要根據 Exif 資訊作處理,例如這張圖片有無旋轉,接下就來介紹怎麼使用 python 的 PIL 模組來讀取圖片的 Exif 資訊。

安裝 PIL

基本上新版本的 Python 應該都有內建 PIL,如果還未安裝 PIL 的話請參考這篇

使用範例

以下範例 ShengYu 是使用一張有 exif 的照片來測試,
print(img) 可印出該檔案的基本資料,如模式,大小,記憶體所在位置,
使用 _getexif 會回傳個字典 dict,之後在用迴圈將 exif 字典裡的東西全部印出來。

pil-read-image-exif.py
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PIL import Image
from PIL.ExifTags import TAGS

img = Image.open("IMG_20181205_xxxxxx.jpg")
print(img)
exif = img._getexif()

if exif is not None:
for (tag, value) in exif.items():
key = TAGS.get(tag, tag)
print(key + ' = ' + str(value))

輸出結果如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
ImageWidth = 4048
ImageLength = 3036
ApertureValue = (200, 100)
ExifImageHeight = 3036
DateTimeDigitized = 2018:12:05 11:10:19
MaxApertureValue = (200, 100)
ExifVersion = b'0220'
ColorSpace = 1
Contrast = 0
Saturation = 0
FocalLength = (4670, 1000)
SubjectDistanceRange = 1
ExposureMode = 0
Make = Google
Model = Pixel XL
SubsecTimeOriginal = 253505
Orientation = 1
YCbCrPositioning = 1
SensingMethod = 2
ExposureBiasValue = (0, 6)
XResolution = (72, 1)
YResolution = (72, 1)
ExposureTime = (33333, 1000000)
ExifInteroperabilityOffset = 18588
ExposureProgram = 2
SceneCaptureType = 0
ISOSpeedRatings = 1208
ResolutionUnit = 2
WhiteBalance = 0
MeteringMode = 2
ComponentsConfiguration = b'\x01\x02\x03\x00'
FNumber = (200, 100)
Software = HDR+ 1.0.163413028z
DateTime = 2018:12:05 11:10:19
ShutterSpeedValue = (491, 100)
Flash = 16
SceneType = b'\x01'
Sharpness = 0
ExifImageWidth = 4048
CustomRendered = 1
FlashPixVersion = b'0100'
SubjectDistance = (337, 1000)
DateTimeOriginal = 2018:12:05 11:10:19
SubsecTime = 253505
ExifOffset = 230
SubsecTimeDigitized = 253505
BrightnessValue = (-169, 100)
MakerNote = b'HDRP...'

PIL.ExifTags 參數的詳細細節請參考這裡

其他參考資料
https://zh.wikipedia.org/wiki/EXIF

相關主題
Python 旋轉圖片 rotate
Python 縮放圖片 resize
Python 裁切裁剪圖片 crop
Python 圖片模糊化 blur
Python 在圖片上繪製文字