0
0

Pythonで画像ファイルのIPTCを更新する(pyexiv2)

Posted at

はじめに

先日、Pythonのpyexiv2を使って、複数の画像ファイルにつけたIPTCのキーワードを集計するという記事を書きました。

当初は、キーワードの集計ができたところでよしとしていたのですが、キーワードの更新もやってみようと思い、試してみました。

環境

  • OS: Windows 11 Home 22H2
  • Python: 64ビット版、3.11.4

インストール

  • pip install pyexiv2

IPTC情報のうち、キーワードを更新する

サンプルの画像ファイルからIPTCのキーワードを取得して、取得したキーワードの末尾に現在日時の文字列を追加するという処理を行っています。

キーワードに限らず、更新したい要素の値を作り込み、「要素名: 値」で辞書を作成、作成した辞書をmodify_iptc()メソッドで更新するという流れになります。

import pyexiv2
import datetime
import pprint

# JPEGファイルを読み込む
img = pyexiv2.Image(r'.\sample.jpg')

# IPTC情報を取得する
iptc_current = img.read_iptc()

# pprintで各データを表示する
print('## IPTC情報、キーワード更新前')
pprint.pprint(iptc_current)
print()

# キーワードに追加するための現在日時の文字列。
now_str = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')

# iptcのキーワードを操作する
# Iptc.Application2.Keywordsが存在しているかどうかの確認が必要
if 'Iptc.Application2.Keywords' in iptc_current:
    # キーワードが存在していたら、現在のキーワードを取得して、現在日時をキーワードに追加する
    keywords = iptc_current.get('Iptc.Application2.Keywords')
    keywords.append(now_str)
else:
    # キーワードが存在していなかったら、現在日時を値としてキーワードを設定する
    keywords = [now_str]

# 更新用のキーワードの辞書を作る
update_keywords = {'Iptc.Application2.Keywords': keywords}

# 辞書を引数にしてmodifyを実行して、キーワードを更新する
img.modify_iptc(update_keywords)

# 更新後の画像からIPTC情報を取得する
iptc_modified = img.read_iptc()

# キーワードを修正した後のIPTC情報を表示する
print('## IPTC情報、キーワード更新後')
pprint.pprint(iptc_modified)
print()

# クローズ処理
img.close()

結果

キーワードに現在日時を追加することができました。

## IPTC情報、キーワード更新前
{'Iptc.Application2.DateCreated': '2022-02-23',
 'Iptc.Application2.Headline': '冬のダム',
 'Iptc.Application2.Keywords': ['2月', '冬', '雪', 'ダム', '雪景色', '青空', 'サンプル'],
 'Iptc.Application2.RecordVersion': '4',
 'Iptc.Application2.TimeCreated': '10:41:18+00:00',
 'Iptc.Envelope.CharacterSet': '\x1b%G'}

## IPTC情報、キーワード更新後
{'Iptc.Application2.DateCreated': '2022-02-23',
 'Iptc.Application2.Headline': '冬のダム',
 'Iptc.Application2.Keywords': ['2月',
                                '冬',
                                '雪',
                                'ダム',
                                '雪景色',
                                '青空',
                                'サンプル',
                                '2023/09/25 23:41:39'],
 'Iptc.Application2.RecordVersion': '4',
 'Iptc.Application2.TimeCreated': '10:41:18+00:00',
 'Iptc.Envelope.CharacterSet': '\x1b%G'}

要素を消す方法

IPTCの要素自体を消すには、「要素名: None」という辞書を作って、作成した辞書をmodify_iptc()メソッドで更新します。

以下はキーワードを空にする例です。

# iptcのキーワードを空にするため、Noneを値にした辞書を作る
keywords_none = {'Iptc.Application2.Keywords': None}

# 辞書を引数にしてmodify実行
img.modify_iptc(keywords_none)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0