How to convert an image to Base64 encoding

How to convert an image to Base64 encoding

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Convert an Image from a URL to Base64 Encoding

Converting an image from a remote URL into a Base64 string is a common requirement when you need to store binary data in a database field, pass it between services without file I/O, or embed assets directly into HTML. The core mechanism relies on the browser's Fetch API or native Node.js modules to retrieve the binary content and then encode that buffer into a text-safe format.

The Fundamental Mechanism

At its simplest, Base64 encoding transforms every three bytes of binary data into four ASCII characters. This ensures the resulting string can be safely transmitted over protocols like JSON or stored in SQL VARCHAR columns without corruption. However, the process requires two distinct steps: fetching the raw resource and encoding that stream.

In a modern JavaScript environment, you don't manipulate the file on disk if it exists only as a URL. Instead, you fetch the data using fetch(). The response body must be treated as an ArrayBuffer or Blob before encoding. If you attempt to read the text directly from the response without handling the binary nature of the image, you will get gibberish.

async function urlToBase64(url) {
  const response = await fetch(url);
  
  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  // Get the raw binary data as an ArrayBuffer
  const blob = await response.blob();
  const arrayBuffer = await blob.arrayBuffer();

  // Convert ArrayBuffer to a typed array (Uint8Array)
  const uint8Array = new Uint8Array(arrayBuffer);

  // Use the built-in TextEncoder or Buffer in Node.js depending on environment
  // For standard browser environments, we often use window.btoa but that 
  // requires a string input, so we typically convert bytes to a string first.
  
  let base64 = '';
  for (let i = 0; i < uint8Array.length; i++) {
    base64 += String.fromCharCode(uint8Array[i]);
  }

  return btoa(base64);
}

This approach is robust because it explicitly handles the binary data as bytes rather than trying to decode it as text prematurely. In Node.js, this logic simplifies significantly using the built-in Buffer class and its .toString('base64') method.

Trade-offs and Performance Considerations

The primary decision point in this workflow is storage versus performance. Storing large images as Base64 strings in a database increases payload size by approximately 33% compared to the original binary file. If your application serves high-resolution photography or video thumbnails, this bloat can impact query times and network transfer speeds significantly.

Another critical pitfall involves character encoding limits. Standard SQL databases often truncate long text fields (e.g., TEXT in MySQL or VARCHAR(MAX) in SQL Server). A high-resolution image might exceed these limits, causing data truncation or silent failures during serialization. Always validate the size of the Base64 string against your storage constraints before attempting the conversion in production.

Furthermore, security implications arise when handling images from untrusted sources. While Base64 itself is a reversible encoding scheme and not encryption, an attacker could theoretically inject malicious scripts if the image content isn't validated. Ensure that any image fetched from an external URL is served over HTTPS to prevent man-in-the-middle attacks that could alter the binary stream before it reaches your encoder.

When to Use This Approach

This technique shines in specific scenarios: single-page applications that need to cache assets locally without HTTP requests, or APIs that accept JSON payloads containing image data for processing by downstream services. If you are building a Laravel application, you can leverage the existing Storage facade to handle temporary files if memory becomes constrained during large conversions, though direct Base64 conversion is often preferred for small thumbnails or icons.

For more complex pipelines where you need to resize or manipulate the image before encoding, libraries like Sharp (in Node.js) or Intervention Image are preferable. These tools handle the binary transformation efficiently and return a stream that can be piped directly into an encoder, avoiding the need to load the entire file into memory as a string first.

Our network