#!--*-- coding: utf-8 --*--
import argparse
import png

'''
功能:往png图中插入与读取隐藏文本信息
方法:修改src_png和dst_png的路径,然后运行
'''


def insert_text_chunk(src_png, dst_png, text):
    '''
    在png中的第二个chunk插入text文本内容
    '''
    reader = png.Reader(filename=src_png)
    chunks = reader.chunks()
    chunk_list = list(chunks)
    print("[INFO]Total src chunks: {}".format(len(chunk_list)))
    chunk_item = tuple([b'tEXt', text])

    #第一个chunk是固定的IHDR,这里把tEXt放在第2个chunk
    index = 1
    chunk_list.insert(index, chunk_item)

    with open(dst_png, 'wb') as dst_file:
        png.write_chunks(dst_file, chunk_list)

def read_text_chunk(src_png, index=1):
    '''
    读取并打印png的第N个chunk
    '''
    reader = png.Reader(filename=src_png)
    chunks = reader.chunks()
    chunk_list = list(chunks)
    print("[INFO]Total src chunks: {}".format(len(chunk_list)))
    print(chunk_list[index])


def parse_args():
    """Parse input arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', dest='inputpng')
    parser.add_argument('-o', dest='outputpng')
    parser.add_argument('-t', dest='text')
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = parse_args()
    insert_text_chunk(src_png, dst_png, text)
    read_text_chunk(dst_png)

https://github.com/Arthurzhangsheng/imgpreprocessing/blob/master/pngread.py

Last modification:November 2nd, 2020 at 05:36 pm