1

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!

Yinan
  • 2,516
  • 4
  • 22
  • 23

4 Answers4

6

You need to open in binary mode:

img = open("Last_Dawn.jpg", 'rb')
Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91
4

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
  • 3,293
  • 18
  • 15
2
open(filename, 'rb')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

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
  • 854,327
  • 234
  • 1,573
  • 1,953