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!

4 Answers 4

6

You need to open in binary mode:

img = open("Last_Dawn.jpg", 'rb')
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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")

Comments

2
open(filename, 'rb')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.