Pythonで画像データのバイナリを文字列として取得したり、

逆にバイナリの文字列から画像データを起こしたりしたい場合。

Pillowを使用。

import io
from PIL import Image

#バイナリにしたい画像を読み込み
tmpimg = Image.open("./imgs/-.png")
with io.BytesIO() as output:
    tmpimg.save(output,format="PNG")
    contents = output.getvalue()#バイナリ取得
    print(contents)#表示
    tmpimg2 = Image.open(io.BytesIO(contents))#バイナリから画像に変換
    tmpimg2.save('image_from_str.png')

#バイナリ文字列としてやる場合はこんな感じ
imgbytes_str = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x0c\x00\x00\x00\x0c\x01\x03\x00\x00\x00l\xbb\xce\xa4\x00\x00\x00\x06PLTE\x00\x00\x00\xff\xff\xff\xa5\xd9\x9f\xdd\x00\x00\x00\x13IDATx\x9cc\xf8\xfc\x81\x01\x8e\x8c\r\x10\x08I\x1c\x00+\xcd\x10\xa5\xa0\xa1\xbf,\x00\x00\x00\x00IEND\xaeB`\x82'
img_from_str = Image.open(io.BytesIO(imgbytes_str))
img_from_str.save('image_from_str2.png')