Skip to content

Instantly share code, notes, and snippets.

@NorimasaNabeta
Created September 26, 2020 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NorimasaNabeta/b2066e6adf2d56747a15b7b44bee8c54 to your computer and use it in GitHub Desktop.
Save NorimasaNabeta/b2066e6adf2d56747a15b7b44bee8c54 to your computer and use it in GitHub Desktop.
embed the meta info into PNG image file.
# -*- mode: python; coding: utf-8-unix -*-
#
#
# @ref: https://pillow.readthedocs.io/en/3.1.x/PIL.html?highlight=PngInfo#PIL.PngImagePlugin.PngInfo
#
import os
from datetime import datetime
from optparse import OptionParser
from PIL.PngImagePlugin import PngImageFile, PngInfo
# PNG SIGNATURE(8)
# IHDR(25)
# 00000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452 .PNG........IHDR
# 00000010: 0000 0227 0000 019d 0802 0000 0046 8b44 ...'.........F.D
# 00000020: 0400 0000 0970 4859 7300 000b 1300 000b .....pHYs.......
# 00000030: 1301 009a 9c18 0000 0a4f 6943 4350 5068 .........OiCCPPh
# ...
# 00012fd0: 5863 8d35 d658 638d 35d6 5863 8d4d 61ff Xc.5.Xc.5.Xc.Ma.
# IEND(12)
# 00012fe0: ff01 003f bd27 8a31 632f 0900 0000 0049 ...?.'.1c/.....I
# 00012ff0: 454e 44ae 4260 82 END.B'.
#
#
#
def inspect_img( img ):
targetImage = PngImageFile(img)
print(targetImage.text)
return (targetImage.text)
#
#
#
# @ref: iTXt chunk: add_itxt(key, value, lang='', tkey='', zip=False)
# @ref: tEXt chunk: add_text(key, value, zip=0)
#
def embeded_text_img( img, img_save, metas, debug=False ):
wellknown_keys = [
'Title', 'Author', 'Description', 'Copyright', 'Creation Time',
'Software', 'Disclaimer', 'Warning', 'Source', 'Comment' ]
targetImage = PngImageFile(img)
if ((not metas is None) and (len(metas.keys()) > 0)):
metadata = PngInfo()
for ky in metas.keys():
metadata.add_text(ky, metas[ky])
targetImage.save(img_save, pnginfo=metadata)
if debug:
inspect_img( img_save )
return
#
#
#
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
sample = { "TestMark" : "Hi There" }
for tp in args:
base = os.path.splitext(os.path.basename(tp))[0]
now = datetime.now()
timestamp = now.strftime("%Y/%m/%d_%H:%M:%S")
sample[ 'Creation Time' ] = timestamp
sample[ 'Software' ] = "png_info.py"
sample[ 'Source' ] = tp
embeded_text_img(tp, base + "_save.png", sample, True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment