end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

pillow for python による tiff画像ファイルへのメタ情報 読み書き

import PIL.Image

def main():
    tag_defs = PIL.TiffTags.TAGS_V2 # metaタグの定義
    
    with PIL.Image.open('ORG.tif') as img:
        # read tag
        for attr_no, attr_val in img.tag_v2.items():
            attr_key = tag_defs.get( attr_no )
            print(attr_no, attr_key.name, attr_val)

        # write tag
        custom_tag = 65000 # custom tag no (65000以上 推奨)
        custom_value = "これはカスタムタグです"
        img.tag_v2[custom_tag] = custom_value.encode('utf-8')

        # 画像を保存
        img.save('custom_tag_image.tiff', tiffinfo=img.tag_v2)

    with PIL.Image.open('custom_tag_image.tiff') as img:
        for attr_no, attr_val in img.tag_v2.items():
            attr_name = ""
            try:
                attr_key = tag_defs.get( attr_no )
                attr_name = attr_key.name
            except Exception as e:
                print( attr_no, "is custom tag.", e)

            if attr_no == 65000:
                attr_val = attr_val.decode("utf-8")
            print(attr_no, attr_name, attr_val)
        
if __name__ == '__main__':
    main()