Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base64 encode/decode binary files in python?

Tags:

python

base64

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

like image 859
Sameera K Avatar asked Nov 30 '17 18:11

Sameera K


People also ask

How do you decode Base64 encoding in Python?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.

How do I decode a file with Base64?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.

How do you convert binary to Base64?

Click on the URL button, Enter URL and Submit. This tool supports loading the Binary File to transform to Base64. Click on the Upload button and select File. Binary to Base64 Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

How do you decode a file in Python?

decode() is a method specified in Strings in Python 2. This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.


1 Answers

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

like image 185
azb_ Avatar answered Nov 08 '22 01:11

azb_