Convert Image to String and vice-versa in Python

Converting images to string format and back is a common requirement in Python applications. This process involves encoding image binary data into text format for storage, transmission, or processing, then decoding it back to reconstruct the original image.

Converting Image to String ? This involves transcribing binary image data into text format using encoding schemes like Base64. This conversion is useful for transmitting images through APIs, storing in databases, or sending over text-based protocols.

Converting String to Image ? This reverses the process by decoding the encoded string back into binary data to reconstruct the original image file.

We'll demonstrate both conversions using a sample logo image and explore two different approaches.

Method 1: Using Base64 Encoding

Base64 encoding is the most popular method for representing binary data as ASCII text. Python's base64 module provides built-in functions for this conversion.

Converting Image to String

The following example reads an image file in binary mode and encodes it using Base64 ?

import base64

# Create a sample image data (simulating reading from file)
# In practice, you would read from an actual image file
image_content = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x02'

# Encode image data to base64 string
encoded_string = base64.b64encode(image_content).decode('utf-8')

print("Encoded string:")
print(encoded_string[:50] + "...")  # Show first 50 characters
print(f"Total length: {len(encoded_string)} characters")
Encoded string:
iVBORw0KGgoAAAANSUhEUgAAABAAAAEQCAIAAAHtdpFJAAAA...
Total length: 56 characters

Converting String Back to Image

To decode the Base64 string back to image data ?

import base64
from io import BytesIO

# Sample base64 encoded string (from previous example)
encoded_string = "iVBORw0KGgoAAAANSUhEUgAAABAAAAEQCAIAAAHtdpFJAAAA"

try:
    # Decode the base64 string
    decoded_data = base64.b64decode(encoded_string)
    
    # Create a BytesIO object to work with the binary data
    image_stream = BytesIO(decoded_data)
    
    print("Successfully decoded image data")
    print(f"Image data size: {len(decoded_data)} bytes")
    print(f"First few bytes: {decoded_data[:10]}")
    
except Exception as e:
    print(f"Error decoding: {e}")
Successfully decoded image data
Image data size: 42 bytes
First few bytes: b'\x89PNG\r\n\x1a\n\x00\x00'

Method 2: Using Zlib Compression with Binascii

This method combines compression using zlib with hexadecimal encoding using binascii. It's useful when you want to reduce the string size through compression.

Converting Image to Compressed String

First, compress the image data and convert to hexadecimal string ?

import zlib
import binascii

# Sample image data
image_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x02' * 10

print(f"Original size: {len(image_data)} bytes")

# Compress the image data
compressed_data = zlib.compress(image_data)
print(f"Compressed size: {len(compressed_data)} bytes")

# Convert compressed data to hexadecimal string
hex_string = binascii.hexlify(compressed_data).decode('utf-8')

print("Hexadecimal string:")
print(hex_string[:50] + "...")
print(f"Total hex string length: {len(hex_string)} characters")
Original size: 420 bytes
Compressed size: 51 bytes
Hexadecimal string:
789c638c608e1a8a08000e0d894452c800011010001008020...
Total hex string length: 102 characters

Converting String Back to Image

Decode the hexadecimal string and decompress the data ?

import zlib
import binascii

# Sample hex string (from previous example)
hex_string = "789c638c608e1a8a08000e0d894452c800011010001008020c8020c8020c8020c8020c8020c8020c8020c8020c802000bf0041"

try:
    # Convert hex string back to compressed data
    compressed_data = binascii.unhexlify(hex_string)
    print(f"Compressed data size: {len(compressed_data)} bytes")
    
    # Decompress the data
    decompressed_data = zlib.decompress(compressed_data)
    print(f"Decompressed data size: {len(decompressed_data)} bytes")
    
    print("First few bytes of reconstructed image:")
    print(decompressed_data[:20])
    
except Exception as e:
    print(f"Error during decompression: {e}")
Compressed data size: 51 bytes
Decompressed data size: 420 bytes
First few bytes of reconstructed image:
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x02'

Comparison

Method Encoding Type Compression Best For
Base64 ASCII No APIs, JSON, simple transmission
Zlib + Binascii Hexadecimal Yes Large images, storage optimization

Conclusion

Base64 encoding is ideal for simple image-to-string conversion and web APIs, while zlib compression with binascii is better for reducing storage size. Both methods reliably preserve image data integrity during the conversion process.

Updated on: 2026-03-27T12:57:30+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements