I'm trying to store an image as text, so that I can do something like this example of a transparent icon for a Tk gui:
import tempfile
# byte literal code for a transparent icon, I think
ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64
# makes a temp file for the transparent icon and saves it
_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, 'wb') as icon_file:
icon_file.write(ICON)
I've tried base 64 encoding, decoding with utf8, converting to bytes and bytearray, and some answers from another post: (Python Script to convert Image into Byte array)
import tempfile, base64, io
# byte literal code for a transparent icon, I think
ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64
# makes a temp file for the transparent icon and saves it
_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, 'wb') as icon_file:
icon_file.write(ICON)
a = open(ICON_PATH, 'rb').read()
b = base64.b64encode(a)
print b # output does not match what ICON equals above
# doesn't work; gives error
# UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 1342: invalid start byte
# b = bytes(a).decode('utf-8')
c = bytearray(a)
print c # prints garbled junk
# gives error AttributeError: __exit__ on Image.open(ICON_PATH) line
with io.BytesIO() as output:
from PIL import Image
with Image.open(ICON_PATH) as img:
img.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
print data
It also doesn't work for b.decode('utf-8') or b.encode('utf-8')