[Python] How to Encode Binary Data (Images, etc.) to Base64 Format

Base64 is an encoding method that converts binary data, such as image files or audio data, into text (strings) composed of only 64 types of alphanumeric characters.

This allows binary data to be sent and received via text-based protocols that cannot handle raw binary (such as sending data via JSON or embedding images directly into HTML).

Here, I will explain how to read an image file and convert it into a Base64 string.

目次

Implementation Example: Converting an Avatar Image to a Base64 String

In this scenario, we read a local image file (user_avatar.png) in binary mode and convert it into a string format suitable for transmission via Web APIs.

Source Code

import base64

# Image file to encode
target_file = "user_avatar.png"

# Error handling in case the dummy file does not exist
try:
    # 1. Open file in binary read mode ('rb')
    # Since it is not text, 'rb' (Read Binary) is mandatory, not 'r'
    with open(target_file, "rb") as f:
        binary_data = f.read()
        
    # 2. Encode binary data to Base64 bytes
    # base64.b64encode() returns bytes type
    b64_bytes = base64.b64encode(binary_data)
    
    # 3. Decode bytes to string (str type)
    # Convert to a normal string to include in JSON, etc.
    b64_string = b64_bytes.decode("utf-8")
    
    print(f"Processed File: {target_file}")
    print(f"Data Size     : {len(binary_data)} bytes")
    print("-" * 30)
    print("--- Base64 String (First 50 chars) ---")
    print(b64_string[:50] + "...") # Displaying only the beginning as it is long
    
    # Bonus: Creating a Data URL format for HTML embedding
    # Format: data:image/png;base64,xxxxxx...
    html_src = f"data:image/png;base64,{b64_string}"
    print("\n--- HTML Embedding Tag ---")
    print(f'<img src="{html_src[:50]}..." />')

except FileNotFoundError:
    print(f"Error: File '{target_file}' was not found.")
    # Example using text data for demonstration
    sample_text = b"Hello Python Base64"
    print(f"\n(Reference) Text encoding result: {base64.b64encode(sample_text).decode()}")

Execution Result (Example)

Processed File: user_avatar.png
Data Size     : 15320 bytes
------------------------------
--- Base64 String (First 50 chars) ---
iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAAX...

--- HTML Embedding Tag ---
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." />

Explanation

1. Reading in Binary Mode (rb)

When opening an image with the open() function, you must specify the mode as "rb" (Read Binary). If you open it in text mode (the default "r"), the OS may attempt to automatically convert newline codes, which will corrupt the data and prevent the image from being read correctly.

2. The Flow of Encoding and Decoding

  1. f.read(): Reads the file content as bytes.
  2. base64.b64encode(): Accepts the bytes and returns Base64 encoded bytes.
  3. .decode("utf-8"): Since Base64 consists only of ASCII characters (alphanumeric + symbols), we decode it using UTF-8 to handle it as a standard Python string (str). This makes it easy to set as a JSON value or save to a text file.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次