-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxpkeyword.py
42 lines (34 loc) · 1000 Bytes
/
xpkeyword.py
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
from PIL import Image
import piexif
def decode(t):
"""
Takes a exif XPKeywords tag and decodes it to a text string
"""
b = bytes(t)
return b[:-2].decode('utf-16-le')
def encode(s):
"""
Takes a text string and encodes it as an exif XPKeywords tag
"""
b = s.encode('utf-16-le') + b'\x00\x00'
return tuple([int(i) for i in b])
def get_tags(file):
"""
Reads the exif XPKeyword tags of an image and returns them as a stirng
"""
im = Image.open(file)
exif_dict = piexif.load(im.info["exif"])
keyword = exif_dict["0th"][piexif.ImageIFD.XPKeywords]
keyword = decode(keyword)
im.close()
return keyword
def write_tags(file, string):
"""
Writes exif XPKeyword tags to an image
"""
im = Image.open(file)
keyword = encode(string)
exif_dict = piexif.load(im.info["exif"])
exif_dict["0th"][piexif.ImageIFD.XPKeywords] = keyword
exif_bytes = piexif.dump(exif_dict)
im.save(file, exif=exif_bytes)