-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimage_metadata.py
More file actions
63 lines (48 loc) · 2.14 KB
/
image_metadata.py
File metadata and controls
63 lines (48 loc) · 2.14 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import os
from PIL import Image, ExifTags, UnidentifiedImageError
import piexif
def metadata_extractor(file_path: str, check=False) -> dict:
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
try:
img = Image.open(file_path)
except UnidentifiedImageError:
raise UnidentifiedImageError("Error: Cannot identify image file '{file_path}'/ file type is not supported.")
exif = img._getexif()
if not exif and not check:
print("\033[94mNo EXIF metadata found.\033[0m")
return {}
exif_dict = {ExifTags.TAGS.get(k, k): v for k, v in exif.items()}
return exif_dict
def clear_metadata(file_path: str, output_path: str):
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
try:
img = Image.open(file_path)
except UnidentifiedImageError:
raise UnidentifiedImageError("Error: Cannot identify image file '{file_path}'/ file type is not supported.")
exif_data = img.info.get('exif')
if not exif_data:
print("\033[94mNo EXIF metadata found to clear.\033[0m")
img.save(output_path)
return
exif_dict = piexif.load(exif_data)
# Remove all metadata tags
for ifd in ('0th', 'Exif', 'GPS', '1st', 'Interop'):
exif_dict[ifd].clear()
# Save the image with the new EXIF data
exif_bytes = piexif.dump(exif_dict)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
img.save(output_path, "jpeg", exif=exif_bytes)
if __name__ == "__main__":
file_path = "/Users/mitz/Desktop/IMG_3794.jpeg"
print("\033[94mOriginal metadata:\033[0m")
metadata = metadata_extractor(file_path=file_path)
for tag, value in metadata.items():
print(f"\033[94m{tag}: {value}\033[0m")
output_path = "/Users/mitz/Desktop/IMG_3794_modified.jpeg"
clear_metadata(file_path, output_path)
print("\033[94mModified metadata:\033[0m")
modified_metadata = metadata_extractor(file_path=output_path)
for tag, value in modified_metadata.items():
print(f"\033[94m{tag}: {value}\033[0m")