W3jar
361 words
2 minutes

How to Convert Images and Image URLs to Base64 in JavaScript

Converting images and image URLs to Base64 in JavaScript involves a few steps, depending on whether you have an image URL or an image file. Here’s a guide for both scenarios:

1. Convert Image URLs to Base64#

To convert an image URL to Base64, you need to fetch the image, read it as a binary string, and then encode it to Base64. Here’s how you can do this:

async function imageUrlToBase64(url) {
    // Fetch the image
    const response = await fetch(url);
    if (!response.ok) throw new Error("Network response was not ok.");

    // Read the response as an ArrayBuffer
    const arrayBuffer = await response.arrayBuffer();

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

    // Convert Uint8Array to a binary string
    const binaryString = Array.from(uint8Array)
        .map((byte) => String.fromCharCode(byte))
        .join("");

    // Convert binary string to Base64
    const base64String = btoa(binaryString);

    return `data:image/jpeg;base64,${base64String}`; // Adjust MIME type if needed
}

// Example usage
imageUrlToBase64("https://example.com/image.jpg")
    .then((base64) => {
        console.log(base64);
    })
    .catch((error) => {
        console.error("Error:", error);
    });

2. Convert Image Files to Base64#

For file inputs (e.g., files selected via an <input type="file"> element), you can use the FileReader API to convert the image to Base64.

Here’s how you can do it:

<input type="file" id="fileInput" accept="image/*" />
<script>
    document
        .getElementById("fileInput")
        .addEventListener("change", function (event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const base64String = e.target.result;
                    console.log(base64String);
                };
                reader.readAsDataURL(file); // This automatically converts to Base64
            }
        });
</script>

Explanation#

  • For Image URLs:

    • fetch(url) retrieves the image data.
    • response.arrayBuffer() reads the image data as an ArrayBuffer.
    • Convert the ArrayBuffer to a binary string and then to a Base64 encoded string.
    • Prepend the Base64 string with the appropriate data URL scheme.
  • For Image Files:

    • FileReader reads the file as a data URL, which is already in Base64 format.
    • e.target.result contains the Base64 encoded string, including the data URL scheme.

Notes#

  • Ensure that the MIME type in the data URL (data:image/jpeg;base64,) matches the actual type of the image. If you’re unsure, you can determine it from the file type or response headers.
  • Be aware of cross-origin issues when dealing with image URLs. Some URLs might have restrictions that prevent them from being fetched and processed due to CORS policies.

Feel free to adapt the code according to your specific requirements!