Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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. Why?

When it tries to read 32 or more bytes, the output will be the same as when it read 16 bytes. Why can I not read more than 16 bytes of the jpeg image?

like image 589
andrepcg Avatar asked Jan 12 '11 00:01

andrepcg


2 Answers

Two issues here:

  1. Set read mode to binary. This way file.read function won't try to convert '\r\n' sequences.

  2. You're trying to print NULL-terminated string to the console. print function finds first zero character in your string and terminates. Use binascii.hexlify to convert it to the hex:


f = open("test.jpg", "rb")
ima = f.read(16)

print "%s" % (binascii.hexlify(ima))
like image 114
yurymik Avatar answered Oct 21 '22 13:10

yurymik


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.

like image 23
brettkelly Avatar answered Oct 21 '22 14:10

brettkelly