How to Convert an Image URL to Base64

This blog explores online tools, JavaScript methods, and even server-side solutions for converting images to Base64

in

How to Convert an Image URL to Base64

Have you ever run into a situation where you needed to include an image directly into an HTML webpage instead of hosting it on a fileserver and linking to it using a URL? For example, let’s say you’re designing a webpage with lots of small decorative images, like background icons or patterns. These images aren’t meant to be SEO-friendly—they’re just design elements that you want to keep embedded within the HTML to reduce the number of HTTP requests. Converting these to base64 strings can help in this situation.

While this approach might make sense for such a highly specific use case (and a few more which you’ll read below), it’s important to recognize that converting images to Base64 and embedding them directly into your HTML is generally not advisable. This technique can significantly increase the size of your HTML file, leading to slower load times, and it can make the code more challenging to manage, especially if you have multiple images. Additionally, it eliminates the benefits of browser caching and content delivery networks (CDNs), which are very helpful for performance and scalability.

If you still need to convert an image to Base64, this guide will walk you through the process, touching upon user-friendly online tools, browser-based JavaScript techniques, and a few framework-specific solutions. Toward the end, you will learn how to integrate these images into web forms and the best practices you should keep in mind when working with web images.

Understanding Base64 Encoding

At its core, Base64 encoding is a text representation for binary data, typically images. The conversion process involves breaking up the image data, a sequence of 0s and 1s, into small chunks.

Process of converting an image file to base64 string

Base64, as the name suggests, uses groups of 6 bits (2 raised to the power of 6 equals 64). Each of these 6-bit sequences then gets mapped to a specific character from a predefined set. This character set is carefully chosen to include only letters (uppercase and lowercase), numbers (0-9), and a few symbols (+ and /) – all elements readily available on a standard keyboard.

Imagine a simple image represented by a long string of 0s and 1s. Base64 encoding splits this string into 6-bit pieces. Each piece is then converted into a single character from the Base64 alphabet. By continuing this process for the entire binary data, you end up with a string of text containing only alphanumeric characters and symbols. This text string is the Base64 encoded version of the original image.

There’s a small catch, though. Not all binary data lengths fall perfectly into groups of 6 bits. To make the encoded strings consistent and decodable, padding characters (usually “=”) are added at the end. These extra characters don’t carry any actual image information but help maintain the structure of the encoded data.

It is important to remember that Base64 encoding doesn’t make the data itself smaller. In fact, the encoded string is typically around 33% larger than the original binary data. This is due to the overhead of adding padding characters and converting smaller binary chunks into single characters. While this size increase might be negligible for small images, it’s a factor to consider when dealing with larger ones.

The larger size of a Base64 string can cause delays on the backend if you’re planning to store and retrieve it from a database (which in itself is a bad idea, given that there are file/blob storage solutions readily available now). It can also impact website loading times, especially for frequent image use. This is because the browser needs to decode the Base64 text back into binary format before displaying the image. This is why Base64 is only useful for transmitting data over the web, and not storing it.

Even when it comes to transmitting data, there are better alternatives to Base64. If you are trying to upload images (or files) through an HTML form, you can use the multipart/form-data encoding to have the browser handle the conversion of binary files into HTTP-compatible format (most often, Base64) internally. If you are planning to embed images into your HTML pages directly as Base64 strings to reduce the number of requests your app makes, you might be inflating your web app’s file sizes, leading to delayed initial renders.

That brings us to the question, where do you even need Base64?

When Should You Use Base64?

While the Base64 format is not as useful as it seemed until some time ago, it still finds its use in a few situations:

  • Embedding small images (such as thumbnails and icons) in HTML pages, to avoid having to make additional requests to get them from the file store. You must note that this makes the images inaccessible via public URLs (hurting SEO) and prevents them from being cached as well. This is why you must only do this for very tiny images that have no significance apart from design.
  • Uploading images to a service that does not accept file uploads (or offers limited file uploads). Base64 can allow you to send image (and file) data as part of the request body, helping you circumvent file storage restrictions.
  • Uploading images from an environment that does not support file uploads through the multipart/form-data encoding out of the box (such as React Native, where you need the RNFetchBlog package to upload multipart/form-data files).
  • Embedding images into emails when sending through server environments. Most email providers support rendering Base64 images in emails, so converting an image to Base64 string and attaching it to the email content as text would be useful in situations where you don’t want to go through the hassle of using a file handling solution for attaching files to the email

So if you are looking to use Base64 images in one of these situations, follow along to learn how to convert an image URL to a Base64 encoded string.

Converting Image URL to Base64

Now that you understand how Base64 encoding works, it’s time to take a look at how you can do it yourself. This section will talk about online Base64 converters and a manual way of converting image URLs to Base64 strings by yourself.

Online Base64 Converter

If you are looking to convert image URLs to Base64 images occasionally, an online Base64 encoder offers a quick and easy solution. These web-based tools typically require you to simply paste the image URL or upload the image file. The converter then handles the conversion process and provides the Base64 format string for you to copy and paste into your code.

While convenient, there are security considerations to keep in mind. Uploading images to third-party websites exposes your data, especially if the images contain sensitive information. For projects involving confidential data, it’s recommended to explore alternative methods like browser-based JavaScript or server-side conversion, which offer more control over your data.

Browser-based JavaScript

Browser-based JavaScript offers a convenient way to convert image URLs to Base64, providing more control and integration within your web application. This method utilizes the Fetch API. Here’s a breakdown of the process:

  1. Fetching the Image: The Fetch API enables you to make a request to the image URL, retrieving the image data as a response object.
  2. Converting to ArrayBuffer: The response object typically contains the image data in a binary format. You can use the arrayBuffer() method to convert this binary data into an ArrayBuffer, a more efficient representation for manipulation.
  3. Base64 Encoding with btoa: Once you have the image data as an ArrayBuffer, you can leverage the built-in btoa function in JavaScript. This function takes the typed version of the ArrayBuffer as input and returns the Base64 encoded string representing the image data.

Here’s a code example that you can use:

  fetch(imageUrl)
      .then(response => response.arrayBuffer())
      .then(buffer => {
          const base64String = btoa(
              new Uint8Array(buffer)
                  .reduce((data, byte) =>
                      data + String.fromCharCode(byte), '')
          );
          console.log(base64String)
      });

While Fetch API and btoa are widely supported in modern browsers, consider checking compatibility for older browsers if needed. Alternative libraries like FileReader API can provide broader browser support.

Node.js

In a Node.js environment, you can achieve the same functionality of converting image URLs to Base64 using built-in modules like https or http to fetch the image and the Buffer class to handle binary data. This approach allows you to convert an image URL to a Base64 on Node-based server-side applications seamlessly.

Here’s a step-by-step breakdown of the process:

  1. Fetching the Image: Use the https or http module to make a request to the image URL. This will retrieve the image data as a response stream.
  2. Collecting the Data: The response stream contains the image data in chunks. You can collect these chunks into an array.
  3. Concatenating the Data: Once all chunks are collected, concatenate them into a single Buffer object.
  4. Base64 Encoding: Use the toString('base64') method on the Buffer object to convert the binary data to a Base64 encoded string.

Here’s a code example that demonstrates this process:

  const https = require('https'); // or 'http' for non-https URLs

  function imageToBase64(url) {
      return new Promise((resolve, reject) => {
          https.get(url, (response) => {
              let data = [];

              response.on('data', (chunk) => {
                  data.push(chunk);
              });

              response.on('end', () => {
                  const buffer = Buffer.concat(data);
                  const base64String = buffer.toString('base64');
                  resolve(base64String);
              });

          }).on('error', (err) => {
              reject(err);
          });
      });
  }

  // Usage example:
  imageToBase64('https://example.com/image.jpg')
      .then(base64String => {
          console.log(base64String);
      })
      .catch(err => {
          console.error('Error:', err);
      })

If you need to convert a Base64 encoded string back to an image file, you can use the fs module to write the data to a file:

  1. Decoding the Base64 String: Use the Buffer class to decode the Base64 string back into binary data.
  2. Writing to a File: Use the fs.writeFile method to write the binary data to an image file.

Here’s a code example:

  const fs = require('fs');

  function base64ToImage(base64String, outputPath) {
      return new Promise((resolve, reject) => {
          const buffer = Buffer.from(base64String, 'base64');

          fs.writeFile(outputPath, buffer, (err) => {
              if (err) {
                  reject(err);
              } else {
                  resolve('File saved successfully.');
              }
          });
      });
  }

  // Usage example:
  const base64String = 'your_base64_string_here';
  const outputPath = 'path/to/output/image.jpg';

  base64ToImage(base64String, outputPath)
      .then(message => {
          console.log(message);
      })
      .catch(err => {
          console.error('Error:', err);
      });

This method provides a robust way to handle image data conversion in a Node.js environment, making it suitable for various backend tasks such as image processing, storage, and manipulation.

React Native

In React Native, you can handle the conversion of image URLs to Base64 and vice versa using the rn-fetch-blob library. You can use the rn-fetch-blob library to fetch the image data from a URL and then convert the fetched response into Base64 format using the base64() method provided by the library.

Here’s a code example using rn-fetch-blob:

  import RNFetchBlob from 'rn-fetch-blob';

  function imageToBase64(url) {
    return RNFetchBlob.config({ fileCache: true })
      .fetch('GET', url)
      .then((response) => response.readFile("base64"))
      .then((base64Str) => console.log(base64Str))
      .catch((error) => {
        console.error('Error:', error);
      });
  }

  // Usage example:
  imageToBase64('https://example.com/image.jpg')
    .then((base64String) => {
      console.log(base64String);
    });

To convert Base64 to an image, you can use the rn-fetch-blob library to decode the Base64 string. You can then use the writeFile method provided by rn-fetch-blob to write the decoded data to a file. Here’s a code example to help you get started:

  import RNFetchBlob from 'rn-fetch-blob';

  function base64ToImage(base64String, outputPath) {
    return RNFetchBlob.fs.writeFile(outputPath, base64String, 'base64')
      .then(() => {
        console.log('File saved successfully.');
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  }

  // Usage example:
  const base64String = 'your_base64_string_here';
  const outputPath = `${RNFetchBlob.fs.dirs.DocumentDir}/image.jpg`;

  base64ToImage(base64String, outputPath);

You might need to enable file storage permissions on the Android/iOS platform to be able to write base64 strings as image files. For Android, you would need to add android.permission.WRITE_EXTERNAL_STORAGE to your AndroidManifest.xml file. For iOS, you might need to follow more detailed steps as listed in their docs.

Python

In Python, you can handle the conversion of image URLs to Base64 and vice versa using libraries like requests for fetching images and base64 for encoding and decoding binary data. This method is efficient and leverages widely-used, well-supported libraries.

To convert image URLs to base64 in Python, you will use the requests library to fetch the image data from a URL. Next, you will read the image data into a bytes object. Then, you will use the base64 library to encode the bytes object into a Base64 string.

Here’s a code example using requests and base64:

  import requests
  import base64

  def image_to_base64(url):
      response = requests.get(url)
      if response.status_code == 200:
          base64_str = base64.b64encode(response.content).decode('utf-8')
          return base64_str
      else:
          raise Exception(f"Failed to fetch image: {response.status_code}")

  # Usage example:
  base64_string = image_to_base64('https://example.com/image.jpg')
  print(base64_string)

To converting Base64 to an image file in Python, you can use the base64 library to decode the Base64 string back into binary data. Then, you can use the open function to write the binary data to an image file.

Here’s a code example using base64 and open:

  import base64

  def base64_to_image(base64_string, output_path):
      image_data = base64.b64decode(base64_string)
      with open(output_path, 'wb') as file:
          file.write(image_data)

  # Usage example:
  base64_string = 'your_base64_string_here'
  output_path = 'path/to/output/image.jpg'

  base64_to_image(base64_string, output_path)

Base64 Encoded Images in Web Apps

A common use-case of Base64 encoding is to embed Base64 images within web apps. Let’s talk about some of the approaches and considerations to keep in mind when using Base64 images in web apps.

Embedding Base64 Image in HTML

Leveraging the data URI scheme, you can directly embed Base64 encoded images within HTML. This scheme allows you to specify the image data type (e.g., PNG, JPEG) and the Base64 encoded string as the source for an image tag (<img>) or a background image in CSS.

Here’s an example of using data URI with an image tag:

  <img src="data:image/png;base64,[your_base64_string_here]">

In this example, the src attribute of the img tag references a data URI. The first part specifies the image format (image/png), followed by a semicolon and then the text “base64,” indicating the encoded data type. Finally, the long string after the comma represents the Base64 encoded image data. This approach allows you to directly embed the image within your HTML without relying on external image files.

Sending Base64 Image Via Forms

While form submission typically handles image uploads efficiently, there might be niche scenarios where you want to send Base64 encoded data as part of a form submission. In such cases, you might want to create a hidden form field and set its value to the Base64 encoded image data.

However, it’s important to note that modern form submission methods like multipart/form-data already handle image uploads effectively and often convert them to the Base64 format on the client side for transmission. Manually encoding and sending Base64 data can be redundant and might impact performance.

Moreover, if you’re using Formspree for your web forms, you don’t need to manually convert images to Base64 strings at all. As mentioned above, Formspree utilizes the browser’s built-in multipart/form-data encoding for uploading files, which automatically handles image uploads and converts them for server-side processing. This eliminates the need for manual Base64 encoding and simplifies your form development process.

Regardless of how you make use of Base64 images, it is important to implement proper validation and sanitization on the server side to prevent malicious code injection. This is especially important if you’re allowing user uploads or processing data from untrusted sources.

Best Practices and Considerations

While Base64 encoding offers unique functionalities, you must use it judiciously to maintain your website’s performance and offer a smooth user experience. Here are some best practices to consider:

  • Target Smaller Images: As mentioned already, the Base64 format adds overhead to file size. It’s best suited for smaller images like icons or logos. For larger images, consider alternative approaches like image optimization techniques or utilizing a Content Delivery Network (CDN) for faster delivery.
  • Explore Alternatives for Large Images: For larger images, explore options like resizing before encoding or implementing lazy loading techniques to defer image loading until they are scrolled into view. This can significantly improve initial page load times.
  • Weigh Benefits vs. Drawbacks: Evaluate if the advantages of Base64 encoded images (like direct embedding) outweigh the potential performance drawbacks for your specific use case. In most scenarios, storing images on a server and referencing them with URLs might be a more efficient and maintainable approach.
  • Prioritize User Experience: Always prioritize user experience. If using Base64 encoding for images impacts website loading times significantly, consider alternative solutions that ensure a fast and responsive user experience.

Final Thoughts

This article looked into converting image URLs to Base64 encoding, a technique often used for embedding images directly in code. You explored the process of Base64 encoding, its advantages and limitations, and various methods for conversion using online tools, browser-based JavaScript, and server-side approaches.

We also discussed best practices for using Base64 encoding effectively, stressing its suitability for smaller images. Remember, if you’re using Formspree, image encoding is handled automatically, simplifying your form development process. In all other cases, make sure to either avoid Base64 images completely or implement them effectively to get the most out of them.


Got Feedback?