0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PNG画像にメタデータをPythonで追加する

Posted at

はじめに

画像にテキストデータ保存できないかなーって思ってたらやり方ありそうだったのでGPTを駆使して探しました
このコードはそれを整理して関数にしています。

コード

from PIL import PngImagePlugin

def add_metadata(input_path: str, output_path: str, metadata: dict):
    img = PngImagePlugin.PngImageFile(input_path)
    imgInfo = img.info
    imgInfo.update(metadata)
    info = PngImagePlugin.PngInfo()
    for k, v in imgInfo.items():
        info.add_itxt(k, v)
    img.save(output_path, pnginfo=info)


def init_metadata(input_path: str, output_path: str, metadata: dict):
    img = PngImagePlugin.PngImageFile(input_path)
    info = PngImagePlugin.PngInfo()
    for k, v in metadata.items():
        info.add_itxt(k, v)
    img.save(output_path, pnginfo=info)


def get_metadata(path: str):
    img = PngImagePlugin.PngImageFile(path)
    info = img.info
    for key, value in info.items():
        print(f'{key}: {value}')

とりあえずこれで初期化と追加と取得ができる。

0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?