如何同步 IPTC 关键字到 EXIF XPKeywords 实现 Windows 资源管理器可见?

解读

国内大多数图像 AI 标注、电商图床、媒体 DAM 系统仍以 IPTC 的 "Keywords" 字段作为权威标签。但 Windows 10/11 资源管理器默认只读取 EXIF 段里的 XPKeywords(0x9C9E,Unicode 小端),导致 IPTC 关键字在本地“看不到”。面试官想知道候选人能否:

  1. 用 Pillow 精准定位两段数据
  2. 处理编码差异(IPTC 是 UTF-8 字节序列,XPKeywords 是 UTF-16LE 以分号分隔)
  3. 保证保存后图像仍能被 Windows 立即识别,且不破坏原有元数据
  4. 兼顾性能与线程安全,适应批量产线

知识点

  • Pillow 的 Image.info 只暴露部分 EXIF,必须导入 ExifTags、TiffImagePlugin、JpegImagePlugin 才能完整读写
  • IPTC 关键字在 APP13 段,键为 0x0404;Pillow 通过 iptc_profile 原始字节返回,需要 python-iptcparse 或手动按 IIM 协议切分
  • XPKeywords 标签号 0x9C9E,类型为 BYTE,但 Windows 要求内容必须是 UTF-16LE 带 BOM 的连续字节,以分号 ';' 分隔,末尾再补两个 0x00
  • 保存时若 format='JPEG',必须加上 exif=img.getexif().tobytes() 才能把修改写回;PNG 需用 info['exif'];WebP 用 info['exif'] 或 info['xmp']
  • 线程安全:Pillow 的 Image 对象本身可并发读,但修改元数据后需要 deepcopy 或锁,避免多线程同时 tobytes() 竞争
  • 国内合规:不得把敏感地理信息写入 EXIF,需提前脱敏

答案

from PIL import Image, ExifTags
from PIL.JpegImagePlugin import get_exif, dump_exif
import struct

def sync_iptc_to_xpkeywords(src_path, dst_path):
    """
    将 IPTC Keywords 同步到 EXIF XPKeywords,使 Windows 资源管理器可见。
    支持 JPEG/PNG/TIFF,输出格式与输入保持一致。
    """
    with Image.open(src_path) as im:
        # 1. 提取并解析 IPTC 关键字
        iptc_bytes = im.info.get('iptc_profile')  # JPEG 的 APP13
        keywords = []
        if iptc_bytes:
            # 简易手动解析 IIM,只取 0x0404
            pos = 0
            while pos < len(iptc_bytes) - 4:
                tag, rec = iptc_bytes[pos+1], iptc_bytes[pos+2]
                if tag == 4 and rec == 4:  # Keywords
                    length = struct.unpack('>H', iptc_bytes[pos+3:pos+5])[0]
                    kw = iptc_bytes[pos+5:pos+5+length].decode('utf-8', errors='ignore')
                    keywords.append(kw)
                    pos += 5 + length
                else:
                    pos += 1
        if not keywords:
            print('无 IPTC 关键字,跳过')
            return

        # 2. 组装 XPKeywords:UTF-16LE + BOM,分号分隔,双 NULL 结束
        xp_str = ';'.join(keywords)
        xp_bytes = 'fffe'.encode('latin1') + xp_str.encode('utf-16le') + b'\x00\x00'

        # 3. 修改 EXIF
        exif = im.getexif()
        exif[0x9C9E] = xp_bytes  # XPKeywords

        # 4. 保存,保持原格式
        save_kwargs = {'exif': exif.tobytes()} if im.format == 'JPEG' else {'exif': exif.tobytes()}
        im.save(dst_path, format=im.format, **save_kwargs)

if __name__ == '__main__':
    sync_iptc_to_xpkeywords('input.jpg', 'output.jpg')

验证:在 Windows 资源管理器 → 属性 → 详细信息 → 标记,即可看到与 IPTC 一致的关键字列表。

拓展思考

  1. 反向同步:当用户在 Windows 侧修改标记后,如何把 XPKeywords 写回 IPTC,实现双向闭环?
  2. 批量性能:面对 10 万张电商图,如何借助 Pillow 的 ImageFile.Parser 多进程队列,把 CPU 密集解析与磁盘 IO 分离,做到每秒 300+ 张?
  3. 无损重写:JPEG 多次保存会累积代损,可先用 im.draft() 降低内存,再用 pyexiv2 或 piexif 仅对元数据段做 transplant,实现“像素零重写”
  4. 国内云厂商 OSS 回源:很多 CDN 会清除 APP13,只保留 EXIF,是否干脆放弃 IPTC,全量转 XMP-dc:subject?如何兼容老系统?
  5. 合规与隐私:XPKeywords 明文存放,若含内部货号或艺人姓名,需先走国密 SM4 加密,再写入自定义标签 0x9286,读取端用配套插件解密,既满足 Windows 可见又防止外泄