【发布时间】:2015-06-13 00:17:27
【问题描述】:
我正在尝试将图像存储为文本,以便我可以为 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)
我已经尝试过 base 64 编码,使用 utf8 解码,转换为字节和字节数组,以及来自另一篇帖子的一些答案:(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
它也不适用于 b.decode('utf-8') 或 b.encode('utf-8')
【问题讨论】:
-
stackoverflow.com/questions/22351254/… 这里提到的解决方案不起作用吗?
-
不,他们没有工作。更新问题以反映它
-
我认为 struct docs.python.org/2/library/struct.html 中的某些东西可能是可能的
-
我看到您正在使用
print语句。这意味着您使用的是 Python 2。Python 3 在许多方面都更好。您可能想要升级。
标签: python