Please bookmark this page to avoid losing your image tool!

Image To Base64 Converter

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
You can edit the below JavaScript code to customize the image tool.
function processImage(originalImg, outputFormat = "png", quality = 0.92) {
    const canvas = document.createElement('canvas');
    
    // Use naturalWidth and naturalHeight for the original image dimensions.
    // These properties represent the intrinsic dimensions of the image.
    // If dimensions are 0, it typically means the image isn't loaded or is an empty image.
    // The Canvas API handles 0x0 dimensions correctly (toDataURL will produce 'data:,' for an empty image).
    canvas.width = originalImg.naturalWidth || 0;
    canvas.height = originalImg.naturalHeight || 0;

    const ctx = canvas.getContext('2d');

    // Check if the 2D rendering context was successfully obtained.
    if (!ctx) {
        // This scenario is highly unlikely in modern browsers for a '2d' context.
        const errorTextArea = document.createElement('textarea');
        errorTextArea.value = "Critical Error: Canvas 2D context is not supported in this browser. Unable to process the image.";
        errorTextArea.setAttribute("readonly", "");
        errorTextArea.style.width = "100%";
        errorTextArea.style.minHeight = "100px";
        errorTextArea.style.boxSizing = "border-box";
        errorTextArea.style.color = "red";
        errorTextArea.style.fontFamily = "monospace";
        return errorTextArea;
    }

    try {
        // Draw the image onto the canvas.
        // This operation can fail if the image is not fully decoded, is corrupted,
        // or in some cases with SVGs if they contain non-renderable content.
        ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);
    } catch (e) {
        console.error("Error drawing image to canvas:", e);
        const errorTextArea = document.createElement('textarea');
        errorTextArea.value = `Error drawing image to canvas. The image might be corrupted, not fully loaded, or of an unsupported type for drawing. Error details: ${e.message}`;
        errorTextArea.setAttribute("readonly", "");
        errorTextArea.style.width = "100%";
        errorTextArea.style.minHeight = "100px";
        errorTextArea.style.boxSizing = "border-box";
        errorTextArea.style.color = "red";
        errorTextArea.style.fontFamily = "monospace";
        return errorTextArea;
    }

    // Determine the MIME type for the output format.
    let mimeType = "image/png"; // Default to PNG.
    const formatLower = String(outputFormat).toLowerCase(); // Ensure outputFormat is a string and normalize case.

    if (formatLower === "jpeg" || formatLower === "jpg") {
        mimeType = "image/jpeg";
    } else if (formatLower === "webp") {
        mimeType = "image/webp";
    }
    // Other formats (e.g., image/bmp) have limited support in canvas.toDataURL an_DECIMALd are not included here.
    // If an unrecognized format is provided, it will default to "image/png" as per initial mimeType value.

    let base64String;
    try {
        // Sanitize and validate the quality parameter for lossy formats.
        let numericQuality = parseFloat(quality);
        if (isNaN(numericQuality) || numericQuality < 0.0 || numericQuality > 1.0) {
            numericQuality = 0.92; // Fallback to default if quality is invalid.
        }

        if (mimeType === "image/jpeg" || mimeType === "image/webp") {
            base64String = canvas.toDataURL(mimeType, numericQuality);
        } else {
            // The quality argument is ignored for 'image/png' and other non-lossy formats.
            base64String = canvas.toDataURL(mimeType);
        }
    } catch (e) {
        // This catch block primarily handles SecurityError from toDataURL().
        // This error occurs if the canvas has been "tainted" by drawing a cross-origin image
        // without appropriate CORS (Cross-Origin Resource Sharing) permissions.
        console.error("Error converting canvas to Data URL:", e);
        const errorTextArea = document.createElement('textarea');
        let errorMessage = `Error converting image to Base64. Details: ${e.message}`;
        if (e.name === "SecurityError") {
             errorMessage = "SecurityError: Could not convert image to Base64. " +
                            "This usually happens when trying to process an image from a different domain (cross-origin) " +
                            "that does not have  CORS headers allowing it to be used in this way. " +
                            "For web images, ensure the server sends 'Access-Control-Allow-Origin' headers, " +
                            "and if using an <img> tag, set its 'crossorigin' attribute (e.g., crossorigin='anonymous').";
        }
        errorTextArea.value = errorMessage;
        errorTextArea.setAttribute("readonly", "");
        errorTextArea.style.width = "100%";
        errorTextArea.style.minHeight = "100px";
        errorTextArea.style.boxSizing = "border-box";
        errorTextArea.style.color = "red";
        errorTextArea.style.fontFamily = "monospace";
        return errorTextArea;
    }

    // Create a textarea element to display the Base64 string.
    // This allows users to easily view and copy the string.
    const resultTextArea = document.createElement('textarea');
    resultTextArea.value = base64String;
    resultTextArea.setAttribute("readonly", ""); // Make the textarea read-only.
    resultTextArea.style.width = "100%";
    resultTextArea.style.minHeight = "150px"; // Provide ample height for typical Base64 strings.
    resultTextArea.style.boxSizing = "border-box"; // Ensures padding/border don't expand total width.
    resultTextArea.style.wordWrap = "break-word"; // Wraps long Base64 string.
    resultTextArea.style.fontFamily = "monospace"; // Optimal for viewing code-like text.

    return resultTextArea;
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

The Image To Base64 Converter is a tool that allows users to convert images into Base64 encoded strings. This is particularly useful for web developers and designers who need to embed images directly within HTML or CSS files without separate file requests, enhancing performance and reducing load times. The tool supports various output formats, including PNG, JPEG, and WEBP, and provides adjustable quality settings for lossy formats. This converter can handle a wide range of use cases such as embedding images in emails, generating QR codes with images, or simplifying image management for web applications.

Leave a Reply

Your email address will not be published. Required fields are marked *