Please bookmark this page to avoid losing your image tool!

Image To Binary Art Generator

(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, threshold = 128, lightChar = '1', darkChar = '0', outputWidthChars = 80, invert = 'false') {
    // --- Parameter Validation and Parsing ---
    // Default values from the function signature are used if a parameter is undefined.
    // This section handles cases where parameters are provided but might be of an invalid type (e.g., string for a number) or out of a valid range.

    let numThreshold = Number(threshold);
    if (isNaN(numThreshold)) { // Fallback if conversion results in NaN (e.g., threshold="abc")
        numThreshold = 128;
    }
    numThreshold = Math.max(0, Math.min(255, numThreshold)); // Clamp to 0-255 range

    let strLightChar = String(lightChar);
    if (strLightChar.length === 0) { // Fallback for empty string
        strLightChar = '1';
    }

    let strDarkChar = String(darkChar);
    if (strDarkChar.length === 0) { // Fallback for empty string
        strDarkChar = '0';
    }

    let numOutputWidthChars = parseInt(String(outputWidthChars), 10);
    if (isNaN(numOutputWidthChars) || numOutputWidthChars <= 0) { // Fallback for NaN or non-positive values
        numOutputWidthChars = 80;
    }
    
    const boolInvert = String(invert).toLowerCase() === 'true';

    // --- Image Validation ---
    // Check if originalImg is valid and loaded.
    // For an HTMLImageElement, naturalWidth/naturalHeight are used. For an Image object, width/height are intrinsic.
    const imgWidth = originalImg.naturalWidth || originalImg.width;
    const imgHeight = originalImg.naturalHeight || originalImg.height;

    if (!originalImg || typeof imgWidth === 'undefined' || typeof imgHeight === 'undefined' || imgWidth === 0 || imgHeight === 0) {
        const errorElement = document.createElement('div');
        errorElement.textContent = 'Error: Invalid image or image not loaded completely (width or height is 0).';
        errorElement.style.color = 'red';
        errorElement.style.fontFamily = 'sans-serif';
        return errorElement;
    }

    // --- Canvas Setup and Image Scaling ---
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // Character aspect ratio correction factor.
    // Monospace characters are often taller than they are wide (e.g., width/height ratio of ~0.5 to ~0.6).
    // This factor helps maintain the visual aspect ratio of the original image in the text art.
    // A value of 1.0 would assume square characters.
    const charAspectRatioCorrection = 0.5; 

    const scaledWidth = numOutputWidthChars;
    // Calculate ScalledHeight based on original aspect ratio and character aspect ratio correction
    const scaledHeight = Math.max(1, Math.floor(numOutputWidthChars * (imgHeight / imgWidth) * charAspectRatioCorrection));

    canvas.width = scaledWidth;
    canvas.height = scaledHeight;

    // Draw the image scaled down to the small canvas. This performs the sampling.
    ctx.drawImage(originalImg, 0, 0, scaledWidth, scaledHeight);

    // --- Pixel Processing ---
    const imageData = ctx.getImageData(0, 0, scaledWidth, scaledHeight);
    const data = imageData.data; // Uint8ClampedArray: [R, G, B, A, R, G, B, A, ...]

    let actualLightChar = strLightChar;
    let actualDarkChar = strDarkChar;

    if (boolInvert) {
        actualLightChar = strDarkChar; // Swap characters if inverted
        actualDarkChar = strLightChar;
    }

    let binaryArtString = '';
    for (let y = 0; y < scaledHeight; y++) {
        for (let x = 0; x < scaledWidth; x++) {
            const index = (y * scaledWidth + x) * 4; // Each pixel is 4 array elements (R,G,B,A)
            const r = data[index];
            const g = data[index + 1];
            const b = data[index + 2];
            // const a = data[index + 3]; // Alpha channel, not directly used in grayscale calculation here.
                                        // Transparent pixels (r=0,g=0,b=0,a=0) will result in grayscale 0.

            // Convert pixel to grayscale (luminance formula)
            const grayscale = 0.299 * r + 0.587 * g + 0.114 * b;

            // Apply threshold to decide if pixel is "light" or "dark"
            if (grayscale >= numThreshold) {
                binaryArtString += actualLightChar;
            } else {
                binaryArtString += actualDarkChar;
            }
        }
        binaryArtString += '\n'; // Add a newline character after each row
    }

    // --- Create Output Element ---
    const preElement = document.createElement('pre');
    preElement.textContent = binaryArtString.trimEnd(); // Remove any trailing newline
    
    // Basic styling for the <pre> element to display binary art nicely
    preElement.style.fontFamily = 'monospace, "Courier New", Courier';
    preElement.style.fontSize = '10px'; // A small default font size
    preElement.style.lineHeight = '0.8'; // Unitless value, relative to font-size. Creates denser lines.
                                         // Use '1.0' or 'normal' for standard spacing.
    preElement.style.whiteSpace = 'pre'; // Ensures whitespace is preserved (default for <pre>)

    return preElement;
}

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 Binary Art Generator is an online tool that converts images into binary art, using ‘1’ and ‘0’ characters to represent different grayscale values of the image. Users can specify a threshold to determine brightness, choose characters for light and dark pixels, and set the width of the output art. This tool is useful for creating visually unique representations of images that can be shared in text formats, used in programming projects, or simply for artistic expression.

Leave a Reply

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