8

I'm trying to encode and decode the same image file using python using following simple code. But every time output file is larger than input file and it can't open. What's the problem in this code?

import base64

with open("img.jpeg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

    decoded_string = base64.b64decode(encoded_string)
    with open("test_img.jpeg", "w") as image_file2:
        image_file2.write(decoded_string);

Original file: https://filebin.ca/3j6aIDlWEYdV/img.jpeg
Result file: https://filebin.ca/3j6arBo85Lcg/test_img.jpeg

4
  • 1
    running this code locally produces an output file that's identical to the input file. Are you sure this is the code you're running? Commented Nov 30, 2017 at 19:03
  • Yes, I just copy pasted my code and I tested this several times. My python version is 2.7.13. Could it be the problem? Commented Nov 30, 2017 at 19:06
  • I'm running 2.7.13 too Commented Nov 30, 2017 at 19:07
  • 1
    Found the problem, problem is, it should be "wb" in the write file. If I change it back to just "w" then file is not readable, if I change it back to "wb" then its working again. Commented Nov 30, 2017 at 19:13

1 Answer 1

6

Try changing the write mode to "wb". You're writing and reading as different formats right now.

Sign up to request clarification or add additional context in comments.

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.