如何使用Python读取JPG文件属性面板中的标签字段?
Python提取JPG文件在Windows资源管理器中显示的「标签」字段实现方案
你用常规EXIF读取方法拿不到这个字段,核心原因是该字段不属于通用EXIF标准范畴,是Windows系统扩展的元数据,存在两种存储形式,对应不同读取逻辑:
方案1:读取内嵌在图片文件内的标签
如果标签是直接写入图片元数据的(文件拷贝到非NTFS格式磁盘、发送给其他设备后标签仍然保留),它实际对应EXIF中ID为40094的XPKeywords自定义字段,采用UTF-16LE编码存储,多标签之间用分号分隔。绝大多数常规EXIF库没有对这个字段做默认解码,所以读不到有效值。
- 安装依赖
pip install pillow - 读取代码
from PIL import Image def get_embedded_tags(img_path): with Image.open(img_path) as img: exif_table = img.getexif() raw_tag_val = exif_table.get(40094) if not raw_tag_val: return [] # 按指定编码解码,去除末尾空字节后拆分多标签 decoded = raw_tag_val.decode("utf-16-le").rstrip("\x00") return [tag.strip() for tag in decoded.split(";") if tag.strip()]
方案2:读取NTFS文件系统存储的标签
如果标签没有写入文件本身,而是存在NTFS备用数据流中(文件拷贝到FAT32/exFAT等非NTFS磁盘后标签会丢失),需要调用Windows系统接口读取属性存储中的值,该方案仅支持Windows环境运行。
- 安装依赖
pip install pywin32 - 读取代码
from win32com.propsys import propsys, pscon def get_system_stored_tags(img_path): prop_store = propsys.SHGetPropertyStoreFromParsingName( img_path, None, propsys.GPS_READ, propsys.IID_IPropertyStore ) tag_value = prop_store.GetValue(pscon.PKEY_Keywords) if not tag_value: return [] return list(tag_value.GetValue())
兼容场景调用逻辑
实际使用时可以先读内嵌元数据标签,再读系统存储标签,结果合并去重即可拿到资源管理器中展示的全部标签:
def get_all_jpg_tags(img_path): tags1 = get_embedded_tags(img_path) tags2 = get_system_stored_tags(img_path) # 合并去重 return list(set(tags1 + tags2))
注意:不要使用仅支持标准EXIF字段解析的库(如未做扩展配置的piexif)读取该字段,这类库默认不会识别微软自定义的XP系列EXIF字段,也不会做对应编码转换,无法拿到正确结果。
内容的提问来源于stack exchange,提问作者Nick Grisanti
相关产品推荐
相关产品推荐

