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
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.
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.
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.
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.
Try changing the write mode to "wb"
. You're writing and reading as different formats right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With