How to Decode Base64 Encoded Image String in Python?
Python Code to Decode Base64 Encoded Image String
import base64
original_string = "Hello there visit www.computerscienceai.com"
# Encode
encoded_string = base64.b64encode(original_string.encode('utf-8'))
# Decode
decoded_string = base64.b64decode(encoded_string).decode('utf-8')
print("Encoded string: ", end="");
print(encoded_string)
print("Decoded string: ", end= "");
print(decoded_string)
'''
Output:
Encoded string: b'SGVsbG8gdGhlcmUgdmlzaXQgd3d3LmNvbXB1dGVyc2NpZW5jZWFpLmNvbQ=='
Decoded string: Hello there visit www.computerscienceai.com
'''
But before decoding image string you need to encode an image to base64 string. You can do that by using the following code.
import base64
with open("img.png", "rb") as imageFile:
imgae_string = base64.b64encode(imageFile.read())
print(image_string)