Base64 in Python (Encode/Decode)
Python provides the `base64` module that makes it easy to work with binary data and encoding schemes like Base64.
Encoding to Base64 in Python
To encode data to Base64 in Python, you can use the `base64` module as follows:
import base64
data = b'Hello World' # Replace with your data
base64_encoded = base64.b64encode(data).decode('utf-8')
print(base64_encoded) # Output: 'SGVsbG8gV29ybGQ='
Decoding from Base64 in Python
To decode a Base64 string in Python, use the `base64` module as follows:
import base64
base64_string = 'SGVsbG8gV29ybGQ=' # Replace with your Base64 string
decoded_bytes = base64.b64decode(base64_string)
decoded = decoded_bytes.decode('utf-8')
print(decoded) # Output: 'Hello World'
Encoding an Image to Base64 in Python
You can easily encode an image to Base64 in Python using the `base64` module and reading the image file as binary:
import base64
with open('path/to/your/image.jpg', 'rb') as image_file:
image_data = image_file.read()
base64_image = base64.b64encode(image_data).decode('utf-8')