Image convert base64: encode and decode in Python
Image convert base64: encode and decode in Python
When you need to image convert base64, you're solving a transport problem: binary image data needs to travel through text-only channels. Email attachments, JSON API payloads, database text fields, webhook bodies — none of these natively handle raw binary. Base64 encoding transforms binary image data into ASCII text, inflating the size by roughly 33% but making it universally transportable. According to HTTP Archive's 2024 Web Almanac, over 28% of websites still embed small images as base64 data URIs in CSS or HTML. In automation workflows, base64 is often the only way to pass images between services that communicate via JSON. CodeWords microservices make this conversion trivial — encode, decode, resize, and route images through your workflow pipeline without managing file storage infrastructure.
Unlike generic AI automation posts, this guide shows real CodeWords workflows — not just theory.
TL;DR
- Base64 encoding converts binary image data to ASCII text, increasing size by ~33% but enabling transport through text-only channels (JSON, XML, email).
- Python's
base64module handles encoding/decoding in two lines; pair it withPillowfor format conversion and resizing. - CodeWords microservices let you build image conversion APIs that accept uploads, convert to base64, and return results — deployed in seconds.
Why convert images to base64?
Base64 is a bridge between the binary world and the text world. Consider it a translation layer — like converting Morse code to written English so it can travel through a channel designed for text.
Common use cases:
- API payloads: Services like OpenAI's Vision API accept base64-encoded images directly in JSON requests
- Email embedding: Inline images in HTML emails use base64 data URIs
- Database storage: Storing small images (icons, avatars, thumbnails) in text columns
- Webhook data: Passing image data through webhook-based workflows where file uploads aren't supported
- CMS content: Embedding images in content management systems that accept rich text with inline media
The trade-off is size: a 100KB image becomes approximately 133KB in base64. For images under 50KB (icons, thumbnails, QR codes), this overhead is negligible. For large images, consider URL-based references instead.
How do you convert an image to base64 in Python?
Prerequisites
- Python 3.9+
Pillowlibrary for image manipulation (pip install Pillow)- A CodeWords workspace
Step 1: Basic encoding
import base64
from pathlib import Path
def image_to_base64(image_path: str) -> str:
image_bytes = Path(image_path).read_bytes()
return base64.b64encode(image_bytes).decode("utf-8")
encoded = image_to_base64("photo.jpg")
print(f"Encoded length: {len(encoded)} characters")
Step 2: Create a data URI
For embedding in HTML or CSS, wrap the base64 string in a data URI:
import mimetypes
def image_to_data_uri(image_path: str) -> str:
mime_type = mimetypes.guess_type(image_path)[0] or "image/png"
encoded = image_to_base64(image_path)
return f"data:{mime_type};base64,{encoded}"
data_uri = image_to_data_uri("logo.png")
Step 3: Decode base64 back to an image
def base64_to_image(encoded_str: str, output_path: str):
image_bytes = base64.b64decode(encoded_str)
Path(output_path).write_bytes(image_bytes)
base64_to_image(encoded, "restored_photo.jpg")
How do you handle image conversion with format changes?
Sometimes you need to convert formats during encoding — receiving a PNG and outputting a JPEG base64 string, or resizing before encoding to reduce payload size.
Step 1: Convert format during encoding
import base64
from io import BytesIO
from PIL import Image
def convert_and_encode(image_path: str, target_format: str = "JPEG", quality: int = 85) -> str:
img = Image.open(image_path)
if img.mode == "RGBA" and target_format == "JPEG":
img = img.convert("RGB")
buffer = BytesIO()
img.save(buffer, format=target_format, quality=quality)
return base64.b64encode(buffer.getvalue()).decode("utf-8")
jpeg_base64 = convert_and_encode("screenshot.png", "JPEG", quality=80)
Step 2: Resize before encoding
def resize_and_encode(image_path: str, max_width: int = 800, max_height: int = 600) -> str:
img = Image.open(image_path)
img.thumbnail((max_width, max_height), Image.LANCZOS)
buffer = BytesIO()
fmt = img.format or "PNG"
img.save(buffer, format=fmt)
return base64.b64encode(buffer.getvalue()).decode("utf-8")
Resizing before encoding is critical for API payloads. The OpenAI Vision API recommends images under 20MB, and smaller images process faster and cost less tokens.
How do you build a base64 image API with CodeWords?
Deploy an image conversion endpoint as a CodeWords microservice:
Step 1: Create the FastAPI service
import base64
from io import BytesIO
from fastapi import FastAPI, UploadFile, HTTPException
from PIL import Image
app = FastAPI()
@app.post("/encode")
async def encode_image(file: UploadFile, max_width: int = 1024, format: str = "JPEG"):
if not file.content_type.startswith("image/"):
raise HTTPException(400, "File must be an image")
contents = await file.read()
img = Image.open(BytesIO(contents))
if max_width and img.width > max_width:
ratio = max_width / img.width
img = img.resize((max_width, int(img.height * ratio)), Image.LANCZOS)
if img.mode == "RGBA" and format == "JPEG":
img = img.convert("RGB")
buffer = BytesIO()
img.save(buffer, format=format, quality=85)
encoded = base64.b64encode(buffer.getvalue()).decode("utf-8")
return {
"base64": encoded,
"data_uri": f"data:image/{format.lower()};base64,{encoded}",
"original_size": len(contents),
"encoded_size": len(encoded),
"dimensions": {"width": img.width, "height": img.height},
}
@app.post("/decode")
async def decode_image(base64_string: str, output_format: str = "PNG"):
try:
image_bytes = base64.b64decode(base64_string)
except Exception:
raise HTTPException(400, "Invalid base64 string")
img = Image.open(BytesIO(image_bytes))
buffer = BytesIO()
img.save(buffer, format=output_format)
return {
"size_bytes": len(buffer.getvalue()),
"dimensions": {"width": img.width, "height": img.height},
"format": output_format,
}
Step 2: Deploy via Cody
Ask Cody: "Deploy this image conversion service." It goes live as a serverless endpoint — accessible from any CodeWords workflow, Slack integration, or external system.
How do you use base64 images with AI vision APIs?
The OpenAI GPT-4o Vision API and Anthropic Claude both accept base64-encoded images. Here's a CodeWords workflow pattern:
import base64
from openai import OpenAI
from pathlib import Path
client = OpenAI()
def analyze_image(image_path: str, prompt: str) -> str:
encoded = base64.b64encode(Path(image_path).read_bytes()).decode("utf-8")
response = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {
"url": f"data:image/jpeg;base64,{encoded}"
}}
]
}]
)
return response.choices[0].message.content
result = analyze_image("receipt.jpg", "Extract the total amount and date from this receipt")
In CodeWords, you get LLM access without API key setup — OpenAI, Anthropic, and Google Gemini are available out of the box.
What are the size limits and performance considerations?
Base64 encoding increases data size by approximately 33%. A 2024 benchmark by web.dev showed that base64-encoded images in CSS files add measurable load time when the total encoded size exceeds 10KB.
Practical limits by context:
- JSON API payloads: Most API gateways cap request bodies at 10-50MB. A 30MB image becomes ~40MB in base64 — potentially exceeding limits.
- Database columns: PostgreSQL TEXT columns can hold up to 1GB, but storing large images in the database is an anti-pattern. Use object storage for files over 100KB.
- Email: Gmail and most providers cap inline images at 25MB total per message.
- WebSocket messages: Typically limited to 1-16MB depending on the server configuration.
For large images, use a two-step approach: upload the file to Google Drive or cloud storage, then pass the URL reference through your workflow instead of the base64 data.
How do you convert base64 images in JavaScript?
For browser-based or Node.js workflows:
// Browser: File to base64
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result.split(",")[1]);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
// Node.js: File to base64
const fs = require("fs");
const base64 = fs.readFileSync("image.png").toString("base64");
// Node.js: base64 to file
fs.writeFileSync("output.png", Buffer.from(base64, "base64"));
FAQs
Does base64 encoding compress the image?
No. Base64 is an encoding, not a compression algorithm. It actually increases size by ~33%. If you need smaller payloads, compress the image first (resize, reduce quality, convert to WebP) and then base64-encode the result.
What's the maximum base64 string length for most APIs?
It depends on the API. OpenAI accepts up to 20MB images. Most REST APIs cap request bodies at 10-50MB. Check your target API's documentation for specific limits.
Can I base64-encode any image format?
Yes. Base64 encoding works on any binary data — JPEG, PNG, GIF, WebP, SVG, TIFF, BMP. The encoding doesn't care about the file format; it operates on raw bytes.
Is base64 encoding secure?
No. Base64 is an encoding, not encryption. Anyone can decode a base64 string. Never use it as a security measure. If you need to protect image data in transit, use HTTPS and proper encryption.
Conclusion
Base64 image conversion is a transport mechanism, not a storage strategy. Use it when text-only channels are your only option — API payloads, webhook bodies, inline email images — and prefer URL references for everything else. The pattern is resize, convert format if needed, encode, transmit, decode at the destination. Build your image processing pipeline in CodeWords — because the next API you integrate with probably expects a base64 string, and your users definitely don't want to wait while you figure out the encoding.




