How to Use Base64 in Python: Encoding, Decoding, and Practical Examples

1. What is Base64? Basic Usage in Python

What is Base64? Base64 is a method of encoding binary data into text format. It is commonly used in email, URLs, and web communication to safely transmit binary data. This technique makes it possible to encode images and files and exchange them securely in a text-based format. Advantages of Using Base64 in Python In Python, you can use the standard library base64 to easily perform Base64 encoding and decoding without additional installation. The following code shows how to encode a string into Base64 format and then decode it back to its original form.
import base64

# Data to encode
data = "こんにちは"
encoded_data = base64.b64encode(data.encode('utf-8'))
print(encoded_data)  # b'44GT44KT44Gr44Gh44Gv'

# Decode back to original data
decoded_data = base64.b64decode(encoded_data).decode('utf-8')
print(decoded_data)  # こんにちは
  • The b64encode() function encodes a byte sequence into Base64 format. encode('utf-8') is used to convert a string into bytes.
  • The b64decode() function decodes the encoded data and restores it to the original string.

2. How to Perform Base64 Encoding in Python

Encoding a String Base64 encoding is done after converting text or data into a byte sequence. The following code shows the procedure for encoding a string in Python.
import base64

# Encode a string
text = "Python Base64"
encoded_text = base64.b64encode(text.encode('utf-8'))
print(encoded_text)  # b'UHl0aG9uIEJhc2U2NA=='
Explanation: The encode('utf-8') method converts a string into bytes, and b64encode() encodes it in Base64 format. The encoded data is displayed as a byte sequence.

3. How Base64 Decoding Works with Examples

Restoring Encoded Data Here is an example of decoding Base64-encoded data back into the original string.
import base64

# Base64 encoded data
encoded_data = b'UHl0aG9uIGlzIGdyZWF0'
# Decode back to original string
decoded_data = base64.b64decode(encoded_data).decode('utf-8')
print(decoded_data)  # Python is great
Key Point: The decoded data is returned as bytes, so decode('utf-8') is used to convert it back into a string. This restores the encoded text to its original form.

4. How to Encode and Decode Image Files with Base64 in Python

Converting Image Files to Base64 Base64 can also encode binary data such as image files. The following example shows how to encode an image file into Base64 and save it in text format.
import base64

# Read an image file and encode in Base64
with open('image.png', 'rb') as img_file:
    encoded_image = base64.b64encode(img_file.read())
    print(encoded_image)
Restoring Image Files The following code decodes an encoded image file and restores it to its original image format.
import base64

# Encoded image data
encoded_image = b'...'  # Encoded data

# Decode and save as an image file
with open('decoded_image.png', 'wb') as img_file:
    img_file.write(base64.b64decode(encoded_image))
Explanation: By using b64encode() to encode an image and b64decode() to decode it, you can restore binary data such as images.

5. Practical Applications of Base64

Use in Web Applications Base64 is extremely useful when exchanging data in web applications and APIs. For example, here is an API that converts an image to Base64 and returns it as a JSON response.
from flask import Flask, jsonify
import base64

app = Flask(__name__)

@app.route('/image')
def get_image():
    with open('image.png', 'rb') as image_file:
        encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
    return jsonify({'image': encoded_image})

if __name__ == '__main__':
    app.run(debug=True)
This API is a simple example that encodes an image in Base64 and returns it in JSON. In web applications, this is useful for storing images in databases or transmitting image data via APIs.

6. Considerations and Limitations of Base64 Encoding

Increased Data Size A major drawback of Base64 encoding is that data size increases by about 33%. This is because Base64 converts every 3 bytes of data into 4 bytes of text. For example, a 1MB image becomes 1.33MB when Base64-encoded. Example of Data Size Increase Encoding a 100KB file will result in approximately 133KB. When frequently exchanging large files, this can impact communication speed and storage space, so it is important to combine optimization or compression techniques.

Summary

This article explained how to perform Base64 encoding and decoding in Python, practical application examples, and the advantages and disadvantages of Base64. Base64 is a very convenient technique for transmitting and storing data, especially in web applications and APIs. However, it is important to consider its limitation of increased data size and use it appropriately in your projects.