views:

130

answers:

4

Hi,

I want to read a image in binary mode so that I could save it into my database, like this:

img = open("Last_Dawn.jpg")
t = img.read()
save_to_db(t)

This is working on Mac. But on Windows, what img.read() is incorrect. It's just a little out of the whole set.

So my first question is: why code above doesn't work in Windows?

And second is: is there any other way to do this?

Thanks a lot!

+5  A: 

You need to open in binary mode:

img = open("Last_Dawn.jpg", 'rb')
Max Shawabkeh
+2  A: 
open(filename, 'rb')
Ignacio Vazquez-Abrams
+4  A: 

You need to tell Python to open the file in binary mode:

img = open('whatever.whatever', 'rb')

See the documentation for the open function here: http://docs.python.org/library/functions.html#open

pib
+2  A: 

Can't say for sure but I do know that the ISO C standard doesn't distinguish between the binary and non-binary modes when calling fopen and yet Windows does.

It's likely that the Python code just uses fopen("Last_Dawn.jpg","r") under the covers (since it's written in C) and this is being opened in Windows in non-binary mode.

This will most likely convert line end characters (LF -> CRLF) and possibly others.

If you yourself specify the mode as 'rb' on your open statement, that should fix it:

img = open("Last_Dawn.jpg", "rb")
paxdiablo