【发布时间】:2018-12-13 06:25:06
【问题描述】:
我想读取 PNG 的字节,并修改它们。我已经尝试过这段代码:
import codecs
ed = input("Would you like to encode or decode?\n(e/d)> ")
image = input("What image would you like to use?\n> ")
if(ed == 'e'):
imagef = codecs.open(image, encoding = "hex")
imagel = imagef.read()
img = imagel.decode('hex')
print(img)
但我收到以下错误:
Would you like to encode or decode?
(e/d)> e
What image would you like to use?
> i.png
Traceback (most recent call last):
File "main.py", line 7, in <module>
imagel = imagef.read()
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 700, in read
return self.reader.read(size)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 503, in read
newchars, decodedbytes = self.decode(data, self.errors)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/hex_codec.py", line 25, in decode
return hex_decode(input, errors)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/hex_codec.py", line 19, in hex_decode
return (binascii.a2b_hex(input), len(input))
binascii.Error: Non-hexadecimal digit found
我该如何解决这个问题?
【问题讨论】:
-
十六进制不是二进制的。您需要以二进制模式读取图像。不要使用
codecs -
@Jean-François Fabre 我不知道如何以二进制模式读取文件。在没有编解码器(使用 open)的情况下读取它时,出现此错误:
Traceback (most recent call last): File "main.py", line 7, in <module> imagel = imagef.read() File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte -
但现在你又再次使用解码器了。 (Python 的默认解码器,旨在读取 UTF8 文本。)PNG 不是任何形式、方式或含义的“编码文本”。阅读有关阅读 bytes 的信息。然后 - only 然后,如果您可以成功读取这些字节 - 请阅读 PNG 规范。请特别注意解释 Flate 压缩的部分,即使对于比您更有经验的程序员来说也很难。然后,放弃并使用库。
标签: python python-3.x hex png