[英]Why can I not read more than 16 bytes of a JPEG file in Python?
I am trying to read a JPG image in Python. 我试图用Python读取JPG图像。
So far i have: 到目前为止,我有:
f = open("test.jpg")
ima = f.read(16)
print "'%s'"% (ima)
It reads 16 bytes and displays the string in console, but it looks like I cannot display more than 32 bytes. 它读取16个字节并在控制台中显示字符串,但看起来我不能显示超过32个字节。 Why?
为什么?
When it tries to read 32 or more bytes, the output will be the same as when it read 16 bytes. 当它尝试读取32个或更多字节时,输出将与读取16个字节时的输出相同。 Why can I not read more than 16 bytes of the jpeg image?
为什么我不能读取超过16个字节的jpeg图像?
Two issues here: 这里有两个问题:
Set read mode to binary. 将读取模式设置为二进制。 This way
file.read
function won't try to convert '\\r\\n' sequences. 这样
file.read
函数不会尝试转换'\\ r \\ n'序列。
You're trying to print NULL-terminated string to the console. 您正在尝试将以NULL结尾的字符串打印到控制台。
print
function finds first zero character in your string and terminates. print
函数在字符串中查找第一个零字符并终止。 Use binascii.hexlify
to convert it to the hex: 使用
binascii.hexlify
将其转换为十六进制:
f = open("test.jpg", "rb")
ima = f.read(16)
print "%s" % (binascii.hexlify(ima))
You probably need to set the open mode to binary: 您可能需要将打开模式设置为二进制:
f = open("test.jpg", "rb") # 'rb' here means "read mode, binary"
See this similar question for a more thorough description. 有关更详细的说明,请参阅此类似问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.