Base64 to Image

Base64 Input0 Characters

Decode Base64 encoded data to previewable images and download, supporting 7+ common formats including PNG/JPG/WebP/GIF/SVG. Automatically detects Data URL prefixes with instant browser preview, ideal for API debugging and encoding validation.

Related

What is Base64 to Image?

Base64 to Image is the reverse process of Base64 encoding: it converts Base64-encoded strings back into original binary image data (such as PNG / JPG / WebP / GIF / SVG formats), allowing direct preview in the browser or download as local image files. This is an essential tool for handling API image responses, inline resources (Data URLs), email attachments in Base64, and similar scenarios.

**Core Principle:** Base64 encodes binary data into 64 printable ASCII characters (A-Z, a-z, 0-9, +, /). Converting to image means restoring this ASCII string back to the original binary byte stream, which the browser then parses into image pixels according to the specified MIME type (image/png, etc.). Data URLs (like `data:image/png;base64,iVBORw0KGgo...`) are Base64 combined with a MIME prefix—this tool automatically recognizes and processes this format.

**Typical Use Cases:** ①API Debugging: Many APIs return image captchas, user avatars, or electronic signatures directly as Base64 strings that frontend developers need to preview; ②Frontend Development: Small icons embedded via Data URL (CSS background-image: url(data:image/png;base64,...)) can be pasted into this tool to see the actual result; ③Email Attachment Restoration: MIME Base64-encoded attachments can be decoded back to original images for storage; ④Web Scraping: Scraped image Base64 can be decoded and saved locally; ⑤OCR Preprocessing: Decode images for use with OCR tools to recognize text content.

**Supported Image Formats:** This tool supports all browser-native image MIME types: PNG (image/png), JPG/JPEG (image/jpeg), WebP (image/webp), GIF (image/gif), SVG (image/svg+xml), BMP (image/bmp), AVIF (image/avif), ICO (image/x-icon), and more. Each format uses different compression algorithms and suits different scenarios: PNG is lossless for icons and screenshots, JPG is lossy for photographs, WebP is recommended for modern browsers, and SVG vector is ideal for icons and logos.

**Decoding Security:** All decoding operations happen in the browser via JavaScript (using `atob()` + `TextDecoder` or the `Blob` API). Image binary data is never uploaded to any server. Base64 strings containing sensitive information (such as user avatars or internal screenshots) can be safely used—all data is automatically cleared when you close the page.

Use Cases

  • Decode API-returned Base64 image data into previewable and downloadable image files
  • Verify that frontend inline image resources (Data URL format) are correctly encoded
  • Confirm Base64 content completeness when debugging image upload APIs
  • Save Base64 images as local PNG/JPG files for design work or documentation
  • Decode email attachment Base64 encodings back to images
  • Restore web-scraped Base64 images and save to disk
  • Decode Data URLs to verify actual SVG icon rendering
  • Convert OCR / AI API-returned Base64 images to local files for viewing

How to Use

  1. Paste Base64-encoded image data (with or without Data URL prefix, e.g., data:image/png;base64,iVBORw0KG...)
  2. Tool automatically detects MIME type and decodes (from Data URL or content header sniffing)
  3. Right panel displays instant image preview with file size and dimensions
  4. Click 'Download' to save as local image file, or right-click 'Save Image As'
  5. If decoding fails, manually specify MIME type or preprocess with Base64 Clean tool

Features

  • Online image preview: Images display directly in browser after decoding, no local download needed
  • Multi-format support: Handles 7+ common image MIME types including PNG / JPG / WebP / GIF / SVG / BMP / AVIF
  • Automatic Data URL detection: Strips data:image/png;base64, prefix automatically and extracts pure Base64 content
  • Pure Base64 input: Supports prefix-free Base64 strings with optional MIME type specification
  • Image file download: One-click saving of decoded images as local PNG/JPG files
  • Real-time character statistics: Shows input character count and decoded byte count instantly for size estimation
  • Error detection: Pinpoints specific error locations on failure (invalid characters, incorrect length, MIME mismatch)
  • Zero server upload: All decoding and preview happens locally in-browser, no servers involved
  • Full reverse compatibility: Pairs with 'Image to Base64' tool for complete bidirectional conversion workflow

Code Examples

JavaScript: Native Browser Decoding + Blob URL Preview

javascript

Decode Base64 and display images in browser using native atob() + TextDecoder + Blob API.

// Base64 → Image (native browser implementation)
function base64ToImage(base64String, mimeType = 'image/png') {
  // 1. Strip Data URL prefix if present
  const clean = base64String.replace(/^data:image\/\w+;base64,/, '');

  // 2. Decode to binary string using native atob()
  const binary = atob(clean);

  // 3. Convert to Uint8Array
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }

  // 4. Create Blob URL for <img> tag preview
  const blob = new Blob([bytes], { type: mimeType });
  const url = URL.createObjectURL(blob);

  // 5. Set img.src to preview
  const img = document.createElement('img');
  img.src = url;
  img.onload = () => {
    console.log(`Image dimensions: ${img.width}x${img.height}`);
    console.log(`File size: ${bytes.byteLength} bytes`);
  };

  return { img, url, size: bytes.byteLength };
}

// Usage example:
const result = base64ToImage('iVBORw0KGgoAAAANSUhEUgAAAAUA...');
document.body.appendChild(result.img);

// Release Blob URL (avoid memory leaks)
setTimeout(() => URL.revokeObjectURL(result.url), 60000);

Python: base64 Library Decode and Save Image

python

Decode Base64 data to image binary stream using Python standard library base64, then save with PIL/Pillow or built-in file operations.

import base64
from pathlib import Path

def base64_to_image(base64_string: str, output_path: str, mime_type: str = 'image/png'):
    """Decode Base64 string and save as image file"""

    # 1. Strip Data URL prefix
    if base64_string.startswith('data:image'):
        # Format: data:image/png;base64,iVBORw0...
        header, base64_string = base64_string.split(',', 1)
        # Auto-extract MIME from header
        if 'image/' in header:
            mime_type = header.split('data:')[1].split(';')[0]

    # 2. Decode
    image_bytes = base64.b64decode(base64_string)

    # 3. Save to file
    output_file = Path(output_path)
    output_file.parent.mkdir(parents=True, exist_ok=True)
    output_file.write_bytes(image_bytes)

    print(f"✅ Saved: {output_file}")
    print(f"   File size: {len(image_bytes):,} bytes")
    print(f"   MIME type: {mime_type}")

    return output_file


# Usage example:
# 1. Base64 string from API response
api_base64_response = "iVBORw0KGgoAAAANSUhEUgAA..."

# 2. Decode and save
base64_to_image(api_base64_response, 'output/captcha.png')

# 3. Optional: Further processing with PIL
try:
    from PIL import Image
    img = Image.open('output/captcha.png')
    print(f"Image dimensions: {img.size}")
    img.save('output/captcha.png', optimize=True)
except ImportError:
    print('Install Pillow for image processing: pip install Pillow')

Java: java.util.Base64 + ImageIO Decode Image

java

Decode image binary stream using Java standard library Base64, with ImageIO / BufferedImage for metadata processing.

import java.io.*;
import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class Base64ToImage {
    public static void main(String[] args) throws Exception {
        String base64String = "iVBORw0KGgoAAAANSUhEUgAA...";
        String mimeType = "image/png";

        // 1. Strip Data URL prefix if present
        if (base64String.startsWith("data:image")) {
            int commaIdx = base64String.indexOf(',');
            String header = base64String.substring(0, commaIdx);
            base64String = base64String.substring(commaIdx + 1);
            // Extract MIME from header
            if (header.contains("image/")) {
                mimeType = header.substring(header.indexOf("data:") + 5, header.indexOf(";"));
            }
        }

        // 2. Base64 decode
        byte[] imageBytes = Base64.getDecoder().decode(base64String);

        // 3. Save to file
        String extension = mimeType.substring("image/".length());
        File outputFile = new File("output." + extension);
        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            fos.write(imageBytes);
        }
        System.out.println("✅ Saved: " + outputFile.getAbsolutePath());
        System.out.println("   File size: " + imageBytes.length + " bytes");

        // 4. (Optional) Read image metadata
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
        BufferedImage image = ImageIO.read(bais);
        if (image != null) {
            System.out.println("Image dimensions: " + image.getWidth() + "x" + image.getHeight());
        }
    }
}

FAQ

Which image formats are supported?

PNG, JPG, WebP, GIF, SVG, BMP, AVIF, ICO, and all other browser-native image MIME types. The tool auto-detects based on MIME prefix in Data URLs or input characteristics; you can also manually specify MIME type in the interface. Selecting the correct format ensures proper browser decoding and display.

Does input require the data:image/png;base64 prefix?

No. Two input formats are supported: ①Pure Base64 strings (e.g., iVBORw0KGgoAA...) require selecting MIME type (PNG/JPG) in the interface; ②Data URL format (e.g., data:image/png;base64,iVBORw0KGgo...) auto-detects MIME type from the prefix and decodes. Both input methods work.

Can I preview directly in the browser?

Yes. Decoded images display directly in the browser via Blob URLs with online preview support. After confirming content is correct, download as local file or copy Data URL for HTML/CSS embedding. The entire preview process requires no network requests.

How is this different from Base64 to File tool?

Base64 to Image is specialized for image formats: ①Automatic MIME type detection; ②Direct browser preview via Blob URLs; ③Automatic file extension setting based on MIME (.png/.jpg etc.); ④Image dimension display. Base64 to File is a general tool suitable for any binary file restoration and download (PDF, ZIP, audio, etc.).

What if the decoded image appears incomplete?

Possible causes: ①Base64 string truncated (check if length is complete); ②Incorrect MIME type specified (e.g., decoding PNG data as JPG); ③Original data itself corrupted. Recommendations: ①Verify source Base64 is complete; ②Try switching MIME types; ③Validate with Base64 Validate tool.

How much larger is Base64 vs original image?

Base64 encoding increases original binary data size by approximately 33% (3 bytes → 4 characters). For example, a 100KB PNG becomes ~133KB as Base64. Therefore Base64 is suitable for small images (<10KB); large images should use HTTP URL transfer directly.

Do you support SVG vector images?

Yes. SVG is an XML-based vector format that can be directly embedded in HTML <img> or CSS background-image after Base64 encoding. After decoding it renders as vectors in the browser with lossless scaling. Note that SVG may contain JavaScript code, so exercise caution regarding XSS security.

How do I save as a specific format?

Click the download button after decoding—the tool automatically adds the appropriate extension based on MIME type (image/png → .png, image/jpeg → .jpg). For format conversion (e.g., PNG → JPG), decode first then convert using other tools (like Canvas / ImageMagick).

Decoded image is blank or corrupted?

Common causes: ①Base64 contains newlines or spaces—preprocess with Base64 Clean tool first; ②Missing padding (=)—this tool auto-completes; ③MIME type doesn't match original data—check source API Content-Type or try other MIME types manually; ④Source Base64 truncated during transmission—re-obtain the complete string.

Do you support large images (>10MB)?

Yes, but browser rendering performance degrades with very large images. 10MB Base64 (~7.5MB original) typically decodes smoothly; over 50MB may trigger memory warnings. Recommendations: ①Use base64-clean to remove whitespace first; ②Decode large images in chunks; ③Ensure sufficient browser memory (4GB+ recommended).

Troubleshooting

Decoded image appears blank

MIME type mismatch or incomplete Base64. Check: 1) Source API Content-Type header; 2) Manually switch MIME type and retry; 3) Verify Base64 string completeness (length matches expected).

InvalidCharacterError decode failure

Base64 string contains illegal characters (spaces, newlines, non-ASCII). First remove all whitespace and illegal characters using Base64 Clean tool, then convert.

Downloaded image has wrong extension

Check that the decoded MIME type matches the original. If source API returns image/jpeg but Base64 data is actually PNG, the downloaded extension will be .jpg but format is PNG. Confirm original format from MIME prefix or Content-Type header.

Browser freezes when decoding large images

Base64 strings over 50MB may cause memory overflow. Recommendations: ①Use base64-clean tool to remove whitespace characters; ②Decode large images in batches (e.g., tile-based splitting); ③Ensure sufficient browser memory (4GB+ available recommended); ④Use server-side Node.js/Python scripts for very large images.

SVG image won't display after decoding

SVG is XML-based vector format—after decoding ensure: 1) MIME type uses image/svg+xml; 2) SVG contains no unescaped special characters; 3) Some browsers restrict JavaScript in SVG for security. Validate SVG with XML parser first.

Glossary

Base64
A binary-to-text encoding scheme that represents binary data using 64 ASCII characters, defined in RFC 4648. This tool performs the reverse: converting Base64 strings back to original image binary data.
Data URL
An inline URL format defined in RFC 2397: data:image/<MIME>;base64,<data>. Can be used directly in HTML img src or CSS background-image. This tool automatically detects and strips the prefix.
MIME Type
Internet media type such as image/png or image/jpeg. Browsers use MIME types to determine how to parse byte streams into images.
PNG
Lossless compressed bitmap format with alpha channel support. Commonly used for icons, screenshots, and images requiring detail preservation. Base64 encoding increases size by approximately 33%.
JPG/JPEG
Lossy compressed bitmap format ideal for photographs. High compression ratio but no transparency support. Base64 encoding increases size by approximately 33%.
WebP
Modern image format developed by Google supporting both lossy/lossless compression and alpha channel. 25-35% smaller than PNG/JPG.
Blob (Binary Large Object)
Browser-native binary object that wraps Base64-decoded byte streams into image Blob URLs for preview and download.

8 Image Formats Comparison

Different image formats use different compression algorithms, features, and suit different scenarios.

FormatMIME TypeCompressionAlphaUse Case
PNGimage/pngLosslessIcons / Screenshots / Logos
JPGimage/jpegLossyPhotos / Landscapes
WebPimage/webpLossy/LosslessModern Web Recommended
GIFimage/gifLossless (256 colors)✅ (1-bit)Small Animations / Simple Icons
SVGimage/svg+xmlVectorLogos / Icons / Illustrations
BMPimage/bmpNoneOptionalWindows System Images
AVIFimage/avifLossy/LosslessNext-Gen Format
ICOimage/x-iconLosslessWebsite favicon

Data URL vs HTTP URL Image Loading

Decoded images can be embedded directly in HTML/CSS as Data URLs—comparison with traditional HTTP URLs.

DimensionData URLHTTP URL
HTTP Requests01
Cache ReuseHardEasy (CDN / Browser)
SizeOriginal + 33%Original Size
Ideal Size< 10 KBAny Size
Compressed TransferNo (already encoded)gzip / Brotli
CSP RestrictionsPossibleGenerally Allowed
Server StorageNot NeededRequired
Offline Access✅ (File-level)❌ (Needs Cache)

5 Common Base64 to Image Errors

Use this table to quickly diagnose issues when decoding errors occur.

Error SymptomPossible CauseSolution
Decode failed: InvalidCharacterErrorContains spaces, newlines, non-Base64 charactersPreprocess with Base64 Clean tool
Image appears blankMIME type mismatch with original dataSwitch to correct MIME (e.g., image/png for PNG data)
Image appears incompleteBase64 string truncatedRe-obtain complete Base64 string
Padding errorURL-safe Base64 omits paddingPad with = using Base64 Padding tool
Browser out of memoryImage too large (> 50MB)Decode in chunks or use image compression

Authoritative References