Base64 Encoder and Decoder

Help Us Improve! Found a bug or have suggestions? Connect with us on X (Twitter) or LinkedIn.

Base64 is a binary-to-text encoding scheme that represents binary data using 64 ASCII characters. This tool provides secure, client-side encoding and decoding of text and files with support for UTF-8 characters, URL-safe encoding, and file processing.

Secure Processing

All encoding/decoding happens in your browser - no data is sent to servers

UTF-8 Support

Full support for international characters and emojis

File Processing

Convert files up to 10MB including images and documents

Quick Examples

Text Encoding
Hello → SGVsbG8=

Basic text to Base64 conversion

URL-Safe Encoding
Hello?→ SGVsbG8_

Safe for URLs and filenames

UTF-8 Support
こんにちは → 44GT44KT44Gr44Gh44Gv

Multi-language support


                        

Practical Examples

Data URI for Images

<img src="data:image/png;base64,iVBORw0KGgo..." alt="Base64 Image">

JWT Token Structure

header.eyJzdWIiOiIxMjM0NTY3ODkwIn0.signature

API Authentication

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

How to Use This Tool

Text Encoding

  1. Enter or paste your text in the input area
  2. Choose URL-safe option if needed
  3. Click "Encode to Base64"
  4. Copy the encoded result
Example:
Input: Hello World
Output: SGVsbG8gV29ybGQ=

File Processing

  1. Switch to "File" tab
  2. Upload or drag & drop your file
  3. Download the encoded text file
  4. Use "Decode" to restore files
Ideal for embedding images in CSS/HTML or preparing files for API transmission

Technical Guide

Base64 Encoding Process

  1. Convert input to binary data
  2. Split into 6-bit chunks
  3. Map to Base64 alphabet (A-Z, a-z, 0-9, +, /)
  4. Add padding (=) if needed
Example:
Text: Man
Binary: 01001101 01100001 01101110
6-bit: 010011 010110 000101 101110
Base64: TWFu

Common Use Cases

  • Data URIs: Embed images in HTML/CSS
  • API Tokens: JWT and authentication
  • Email: MIME attachments
  • Binary Data: Safe text transmission
Data URI Example:
data:image/png;base64,iVBORw0KGgo...

Best Practices

When to Use Base64

  • Embedding small images (< 1KB)
  • Sending binary data as text
  • Creating data URIs
  • Encoding authentication tokens

When Not to Use Base64

  • Large files (increases size by ~33%)
  • Already text-safe data
  • When bandwidth is limited
  • Critical performance scenarios

Implementation Examples

JavaScript
// Encode
const encoded = btoa('Hello, World!');
console.log(encoded); // SGVsbG8sIFdvcmxkIQ==

// Decode
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // Hello, World!
Python
import base64

# Encode
encoded = base64.b64encode(b'Hello, World!')
print(encoded) # b'SGVsbG8sIFdvcmxkIQ=='

# Decode
decoded = base64.b64decode('SGVsbG8sIFdvcmxkIQ==')
print(decoded) # b'Hello, World!'
document.getElementById('textSection').style.display = tab === 'text' ? 'block' : 'none'; document.getElementById('fileSection').style.display = tab === 'file' ? 'block' : 'none'; document.querySelectorAll('.nav-link').forEach(link => { link.classList.toggle('active', link.innerText.toLowerCase() === tab); }); // Keep result visible if there's content const hasResult = document.getElementById('result').textContent.trim().length > 0; document.querySelector('.shared-result').style.display = hasResult ? 'block' : 'none'; } function encodeText() { const input = document.getElementById('inputText').value; const urlSafe = document.getElementById('urlSafeToggle').checked; try { // Convert string to UTF-8 bytes let encoded = btoa(unescape(encodeURIComponent(input))); if (urlSafe) { encoded = encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); } document.getElementById('result').textContent = encoded; document.getElementById('errorMessage').style.display = 'none'; } catch (e) { document.getElementById('errorMessage').textContent = 'Error: Invalid input for encoding'; document.getElementById('errorMessage').style.display = 'block'; } } function decodeText() { let input = document.getElementById('inputText').value.trim(); try { // Handle URL-safe format input = input.replace(/-/g, '+').replace(/_/g, '/'); // Add padding if necessary while (input.length % 4) input += '='; // Decode UTF-8 bytes back to string const decoded = decodeURIComponent(escape(atob(input))); document.getElementById('result').textContent = decoded; document.getElementById('errorMessage').style.display = 'none'; } catch (e) { document.getElementById('errorMessage').textContent = 'Error: Invalid Base64 input'; document.getElementById('errorMessage').style.display = 'block'; } } function copyResult() { const text = document.getElementById('result').textContent; navigator.clipboard.writeText(text).then(() => { const btn = document.querySelector('.copy-btn'); btn.innerHTML = ' Copied!'; setTimeout(() => btn.innerHTML = ' Copy', 2000); }); } function handleFileSelect(event) { const file = event.target.files[0]; const fileError = document.getElementById('fileError'); const fileInfo = document.getElementById('fileInfo'); const result = document.getElementById('result'); // Reset messages fileError.style.display = 'none'; fileInfo.style.display = 'none'; result.textContent = ''; if (!file) return; // Validate file type const allowedTypes = { 'image/jpeg': 5, 'image/png': 5, 'image/gif': 5, 'image/webp': 5, 'application/pdf': 10, 'text/plain': 10, 'application/json': 2, 'text/xml': 2, 'text/csv': 2 }; const maxSize = allowedTypes[file.type] || 0; if (!maxSize) { fileError.textContent = `Unsupported file type: ${file.type}`; fileError.style.display = 'block'; return; } // Validate file size if (file.size > maxSize * 1024 * 1024) { fileError.textContent = `File too large. Maximum size for ${file.type}: ${maxSize}MB`; fileError.style.display = 'block'; return; } // Show loading message fileInfo.textContent = 'Processing file...'; fileInfo.style.display = 'block'; const reader = new FileReader(); reader.onload = function (e) { try { const base64 = e.target.result; document.getElementById('result').textContent = base64; document.getElementById('downloadBtn').style.display = 'block'; // Show download button fileInfo.textContent = 'File encoded successfully!'; } catch (error) { fileError.textContent = 'Error encoding file: ' + error.message; fileError.style.display = 'block'; fileInfo.style.display = 'none'; document.getElementById('downloadBtn').style.display = 'none'; // Hide download button on error } }; reader.onerror = function () { fileError.textContent = 'Error reading file: ' + reader.error; fileError.style.display = 'block'; fileInfo.style.display = 'none'; }; reader.readAsDataURL(file); } function formatFileSize(bytes) { if (bytes < 1024) return bytes + ' B' ; if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB' ; return (bytes / 1048576).toFixed(1) + ' MB' ; } function handleDragOver(event) { event.preventDefault(); event.currentTarget.classList.add('dragover'); } function handleDragLeave(event) { event.preventDefault(); event.currentTarget.classList.remove('dragover'); } // Add this CSS to your existing styles const styleSheet=document.createElement('style'); styleSheet.textContent=` .file-input-zone { border: 2px dashed #007bff; transition: all 0.3s ease; } .file-input-zone.dragover { background: rgba(0,123,255,0.1); border-color: #0056b3; } .file-input-zone:hover { border-color: #0056b3; background: rgba(0,123,255,0.05); } .shared-result { display: none; } #result { max-height: 500px; overflow: auto; } .btn-group-sm .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; } `; document.head.appendChild(styleSheet); // Add result view toggle functionality function toggleResultView(view) { const result=document.getElementById('result'); const content=result.textContent; if (view==='wrapped' ) { result.style.whiteSpace='pre-wrap' ; result.style.wordBreak='break-all' ; } else { result.style.whiteSpace='pre' ; result.style.wordBreak='normal' ; } } function switchFileOp(op) { document.getElementById('fileEncodeSection').style.display=op==='encode' ? 'block' : 'none' ; document.getElementById('fileDecodeSection').style.display=op==='decode' ? 'block' : 'none' ; // Update active tab document.querySelectorAll('.nav-pills .nav-link').forEach(link=> { link.classList.toggle('active', link.textContent.toLowerCase().includes(op)); }); } function decodeAndDownload() { const decodeButton = document.getElementById('decodeButton'); const encodedText = decodeButton.dataset.encodedContent; const filename = document.getElementById('outputFilename').value.trim(); const extension = document.getElementById('fileExtension').value; const fileError = document.getElementById('fileError'); const fileInfo = document.getElementById('fileInfo'); // Reset messages fileError.style.display = 'none'; fileInfo.style.display = 'none'; // Validate input if (!encodedText) { fileError.textContent = 'Please paste Base64 encoded data'; fileError.style.display = 'block'; return; } if (!filename) { fileError.textContent = 'Please enter a filename'; fileError.style.display = 'block'; return; } if (!extension) { fileError.textContent = 'Please select a file type'; fileError.style.display = 'block'; return; } try { // Handle both data URL and raw base64 let base64Data = encodedText; if (encodedText.includes(',')) { base64Data = encodedText.split(',')[1]; } // Decode base64 const byteCharacters = atob(base64Data); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset +=512) { const slice=byteCharacters.slice(offset, offset + 512); const byteNumbers=new Array(slice.length); for (let i=0; i < slice.length; i++) { byteNumbers[i]=slice.charCodeAt(i); } byteArrays.push(new Uint8Array(byteNumbers)); } // Create blob and download const blob=new Blob(byteArrays); const downloadLink=document.createElement('a'); downloadLink.href=URL.createObjectURL(blob); downloadLink.download=filename + extension; // Trigger download document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); // Show success message fileInfo.textContent='File decoded and downloaded successfully!' ; fileInfo.style.display='block' ; } catch (error) { fileError.textContent='Invalid Base64 data or decoding error' ; fileError.style.display='block' ; } } // Add auto-detection for file type from data URL document.getElementById('base64Input').addEventListener('input', function (e) { const input=e.target.value.trim(); if (input.startsWith('data:')) { const match=input.match(/^data:([^;]+);/); if (match) { const mimeType=match[1]; const extensionSelect=document.getElementById('fileExtension'); // Map MIME types to extensions const mimeToExt={ 'image/jpeg' : '.jpg' , 'image/png' : '.png' , 'application/pdf' : '.pdf' , 'text/plain' : '.txt' }; if (mimeToExt[mimeType]) { extensionSelect.value=mimeToExt[mimeType]; } } } }); // Add these new functions to your existing JavaScript function downloadEncodedFile() { const encodedContent=document.getElementById('result').textContent; const file=document.getElementById('fileInput').files[0]; if (!encodedContent || !file) return; // Create blob and trigger download const blob=new Blob([encodedContent], { type: 'text/plain' }); const downloadLink=document.createElement('a'); downloadLink.href=URL.createObjectURL(blob); downloadLink.download=`${file.name}_encoded.txt`; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } function handleEncodedFileSelect(event) { const file=event.target.files[0]; if (!file) return; if (file.type !=='text/plain' ) { showFileError('Please upload a .txt file containing encoded data'); return; } const reader=new FileReader(); reader.onload=function (e) { try { const encodedText=e.target.result; // Store encoded data in a data attribute const decodeButton=document.getElementById('decodeButton'); decodeButton.dataset.encodedContent=encodedText; decodeButton.disabled=false; // Try to detect file type from the encoded data detectFileTypeFromEncoded(encodedText); // Show info about loaded file const decodedFileInfo=document.getElementById('decodedFileInfo'); decodedFileInfo.textContent=`Loaded: ${file.name} (${formatFileSize(file.size)})`; decodedFileInfo.style.display='block' ; showFileInfo('Encoded file loaded successfully'); } catch (error) { showFileError('Error reading encoded file'); } }; reader.onerror=()=> showFileError('Error reading file'); reader.readAsText(file); } function detectFileTypeFromEncoded(encodedText) { const fileExtension = document.getElementById('fileExtension'); if (encodedText.startsWith('data:')) { const match = encodedText.match(/^data:([^;]+);/); if (match) { const mimeType = match[1]; const mimeToExt = { 'image/jpeg': '.jpg', 'image/png': '.png', 'application/pdf': '.pdf', 'text/plain': '.txt' }; if (mimeToExt[mimeType]) { fileExtension.value = mimeToExt[mimeType]; } } } } // Update handleFileSelect function function handleFileSelect(event) { const file = event.target.files[0]; const fileError = document.getElementById('fileError'); const fileInfo = document.getElementById('fileInfo'); const result = document.getElementById('result'); // Reset messages fileError.style.display = 'none'; fileInfo.style.display = 'none'; result.textContent = ''; if (!file) return; // Validate file type const allowedTypes = { 'image/jpeg': 5, 'image/png': 5, 'image/gif': 5, 'image/webp': 5, 'application/pdf': 10, 'text/plain': 10, 'application/json': 2, 'text/xml': 2, 'text/csv': 2 }; const maxSize = allowedTypes[file.type] || 0; if (!maxSize) { fileError.textContent = `Unsupported file type: ${file.type}`; fileError.style.display = 'block'; return; } // Validate file size if (file.size > maxSize * 1024 * 1024) { fileError.textContent = `File too large. Maximum size for ${file.type}: ${maxSize}MB`; fileError.style.display = 'block'; return; } // Show loading message fileInfo.textContent = 'Processing file...'; fileInfo.style.display = 'block'; const reader = new FileReader(); reader.onload = function (e) { try { const base64 = e.target.result; document.getElementById('result').textContent = base64; document.getElementById('downloadBtn').style.display = 'block'; // Show download button fileInfo.textContent = 'File encoded successfully!'; } catch (error) { fileError.textContent = 'Error encoding file: ' + error.message; fileError.style.display = 'block'; fileInfo.style.display = 'none'; document.getElementById('downloadBtn').style.display = 'none'; // Hide download button on error } }; reader.onerror = function () { fileError.textContent = 'Error reading file: ' + reader.error; fileError.style.display = 'block'; fileInfo.style.display = 'none'; }; reader.readAsDataURL(file); } function showFileError(message) { const fileError = document.getElementById('fileError'); const fileInfo = document.getElementById('fileInfo'); fileError.textContent = message; fileError.style.display = 'block'; fileInfo.style.display = 'none'; } function showFileInfo(message) { const fileError = document.getElementById('fileError'); const fileInfo = document.getElementById('fileInfo'); fileInfo.textContent = message; fileInfo.style.display = 'block'; fileError.style.display = 'none'; }