AI workflows

Base64 decoding and encoding with AI

AI workflows·· 7 min read

Use Base64 in AI workflows: encode images and audio locally, choose raw Base64 or Data URLs, verify exact bytes, and debug common API errors.

Where AI helps—and where a codec belongs

An AI assistant can explain an unfamiliar payload, write a conversion script, or help diagnose an API error. For the conversion itself, use a deterministic Base64 library: its output must preserve every byte. Asking a language model to generate or reconstruct a long encoded string adds an unnecessary chance of truncation or alteration.

A useful division of work is: let AI help write and review the code; let the codec transform the data; let tests verify the result. An agent with a code-execution tool can run that codec too. Check the execution environment and where files are sent before giving it private data.

This article is a guide to using Base64 alongside AI. The tools on base64.date run locally in your browser; they do not call an AI service.

Why AI APIs still use Base64

Images and recordings are binary files. Base64 provides a text representation that can fit inside a JSON request. It preserves the bytes; it does not describe the picture, transcribe speech, compress a file, or encrypt anything.

Standard padded Base64 has a length of 4 × ceil(byte_count / 3). A 3 MiB file becomes 4 MiB of Base64 before the JSON envelope is added. Small inputs can have proportionally more overhead. The standard alphabet and padding rules are defined in RFC 4648 §4.

For a multimodal request, put media into the API’s documented image or audio field. A long Base64 string pasted into an ordinary text prompt is not a reliable substitute for a media attachment. Request byte limits and model token accounting are different measurements; do not estimate media pricing from the Base64 character count alone.

Raw Base64, Data URL, or file reference?

RepresentationWhat it containsWhen to use it
Raw Base64iVBORw0KGgo… with MIME information in a separate fieldThe API explicitly asks for encoded bytes.
Data URLdata:image/png;base64,…The receiving field accepts a complete Data URL.
File ID or URLA reference to separately stored mediaThe API supports references, especially for repeated use or larger files.

These forms are not interchangeable. For example, Claude’s image content blocks can use a Base64 source with a separate media type; its vision documentation also describes URL and file sources. See the Claude vision input formats.

The Gemini API represents inline bytes with MIME information in its inlineData structure. SDKs may accept bytes and encode them for you, so follow the SDK’s expected type rather than encoding a second time. See the Gemini inline data reference.

Provider field names, supported models and limits change. Consult the specific endpoint’s documentation before sending a request; the examples here do not submit requests or require an API key.

Prepare an image or audio payload locally

  1. Open Image ↔ Base64 or Audio ↔ Base64 and select one local file.
  2. Check its detected type and size. Our image tool accepts PNG, JPEG, GIF and WebP up to 5 MiB, with a preview limit of 20 megapixels and 16,384 pixels per side. Audio accepts supported WAV, MP3, FLAC, Ogg Vorbis/Opus and M4A files up to 10 MiB.
  3. Select Pure Base64 or Data URL to match your API field. Copy full output or save the encoded text. The on-screen preview may be shortened; the copy and save actions use the complete result.
  4. To inspect an encoded response, select the reverse direction, paste its payload, and decode. Confirm the preview and download the original bytes if needed.

Encoded input is limited to 7 MiB for images and 14 MiB for audio. These are our tool limits, not an AI provider’s limits. Media conversion and preview happen in browser memory, and these two tool pages do not load analytics scripts.

Audio format matters. Raw PCM returned by some speech workflows is not a WAV file. Changing a filename or MIME label does not add a container or change a codec. Our audio tool does not accept raw PCM or WebM; use a suitable local audio library to package or transcode those bytes before previewing them. Base64 encoding alone never performs that step.

Python examples: encode, decode, and verify

Start with a harmless text round trip. Encode text as UTF-8 before converting its bytes to Base64; only decode recovered bytes as UTF-8 when you know they are text.

import base64

original = "Hello, 世界 👋".encode("utf-8")
encoded = base64.b64encode(original).decode("ascii")
restored = base64.b64decode(encoded, validate=True)

assert restored == original
print(encoded)
print(restored.decode("utf-8"))

For a local image, read binary bytes and keep the MIME prefix separate. This PNG example enforces a 5 MiB input limit, checks the signature, and verifies a round trip without sending anything to a server.

import base64
from pathlib import Path

limit = 5 * 1024 * 1024
with Path("sample.png").open("rb") as source:
    original = source.read(limit + 1)
if not original or len(original) > limit:
    raise ValueError("Choose a non-empty PNG up to 5 MiB")
if not original.startswith(b"\x89PNG\r\n\x1a\n"):
    raise ValueError("Expected a PNG signature")

raw_base64 = base64.b64encode(original).decode("ascii")
data_url = "data:image/png;base64," + raw_base64
restored = base64.b64decode(raw_base64, validate=True)
assert restored == original

# Choose raw_base64 or data_url for your API's documented field.
# No upload, file overwrite, or request is performed here.
print(f"Verified {len(restored)} original bytes")

The signature check is not complete image validation. A successful Base64 decode also does not prove a file is safe or playable. Python’s validate=True rejects non-alphabet input instead of silently discarding it; it is not a media validator or a promise of every protocol’s canonical rules. See Python’s Base64 documentation.

A useful prompt for your coding assistant

Describe your requirement without including private media or credentials. Ask the assistant to work from the relevant API documentation and verify its implementation.

Write a local Python helper for the image field described in the API documentation I provide. Confirm whether the field requires bytes, raw Base64, a Data URL, or a file reference. Enforce an input size limit before reading the whole file. Keep binary data as bytes, do not print payloads or credentials, and do not send any network requests. Add a round-trip test that compares the decoded bytes with the original. Explain what the validation does and does not check.

Review the generated code and run it with a small synthetic file first. If a workflow needs a network request, make that a separate, explicit step with the appropriate credentials and destination.

Common errors and what to check

“Invalid Base64” or padding errors
Check for truncation, markdown fences, a Data URL prefix in a raw field, or the wrong alphabet. Standard Base64 uses + and /; Base64URL uses - and _. Use the protocol guide before changing padding or whitespace settings.
The API accepts the request but rejects the image
Confirm that the MIME type describes the actual file. Encoding a JPEG and labeling it PNG does not convert the image. Check the provider’s supported formats, dimensions and decoded size limits.
The recovered file contains another encoded string
The payload may have been encoded twice. Check whether an SDK already handles encoding and compare a known small input through the entire pipeline.
Decoded audio does not play
Verify the container, codec, and any raw-audio parameters such as sample rate and channel count. Browser playback support varies; Base64 success does not establish audio validity.
The request is too large
Measure the encoded body, including JSON. Resize or compress media with an appropriate media tool, or use a supported file-reference workflow. Base64 itself does not reduce file size.

Privacy and alternatives for production

Base64 is reversible. Treat an encoded private recording, screenshot, or credential with the same care as the original. Pasting it into a hosted AI chat or sending it to an API shares that content with the service. Local conversion on this website does not make a later upload private.

Avoid logging request bodies, encoded media or signed URLs. Use synthetic fixtures when asking an assistant for help. For highly sensitive material, use an approved local environment and review the limits of browser-local processing.

For large or reused media, consider a provider’s upload API and file IDs, multipart uploads, or an access-controlled file URL when supported. These approaches avoid repeatedly embedding the same bytes in JSON; they still require appropriate access controls and retention decisions. A signed URL is a temporary credential, and the provider must be able to fetch it before it expires.

Start with the simplest format your endpoint supports, verify exact bytes with ordinary code, and use AI for explanation and implementation help. For related background, read why Base64 is used and why it is not encryption.

← All articles