Please bookmark this page to avoid losing your image tool!

Image Alphabet Translator Tool

(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.
/**
 * Translates an image into a character-based representation (ASCII/character art) on a canvas.
 * This function maps the brightness of image regions to characters from a given alphabet string.
 *
 * @param {HTMLImageElement} originalImg The source image object to process.
 * @param {string} [alphabet='@%#*+=-:. '] The string of characters to use for the translation, typically ordered from darkest to lightest representation.
 * @param {number} [resolution=10] The size of the pixel block to sample for each character. A smaller number means higher detail and a larger output.
 * @param {number} [isInverted=0] A flag to invert the brightness mapping. If 1, light areas of the image get dark characters, and vice-versa. This also inverts the background/foreground colors.
 * @returns {Promise<HTMLCanvasElement>} A promise that resolves with a canvas element containing the character art.
 */
async function processImage(originalImg, alphabet = '@%#*+=-:. ', resolution = 10, isInverted = 0) {
    // 1. Sanitize and validate parameters.
    alphabet = String(alphabet);
    if (!alphabet) {
        alphabet = '@%#*+=-:. '; // Fallback if an empty string is provided.
    }
    resolution = Math.max(1, Number(resolution) || 10);
    isInverted = Number(isInverted) || 0;

    // 2. Create a temporary canvas for downsampling the image.
    // This efficiently averages the colors of the pixel blocks corresponding to each character.
    const downsampleCanvas = document.createElement('canvas');
    const downsampleCtx = downsampleCanvas.getContext('2d');

    const charWidth = Math.floor(originalImg.width / resolution);
    const charHeight = Math.floor(originalImg.height / resolution);

    // If the resolution is so high that it results in 0 characters, return an empty canvas.
    if (charWidth === 0 || charHeight === 0) {
        const emptyCanvas = document.createElement('canvas');
        emptyCanvas.width = 1;
        emptyCanvas.height = 1;
        return emptyCanvas;
    }

    downsampleCanvas.width = charWidth;
    downsampleCanvas.height = charHeight;
    downsampleCtx.drawImage(originalImg, 0, 0, charWidth, charHeight);

    const imageData = downsampleCtx.getImageData(0, 0, charWidth, charHeight);
    const data = imageData.data;

    // 3. Create the final output canvas.
    const outputCanvas = document.createElement('canvas');
    const outputCtx = outputCanvas.getContext('2d');

    // Define font properties. Using a monospace font is crucial for alignment.
    const fontSize = resolution;
    const font = `${fontSize}px 'Courier New', Courier, monospace`;
    outputCtx.font = font;

    // Await for fonts to be ready to prevent rendering with a fallback font.
    // This is good practice even for web-safe fonts to avoid race conditions.
    await document.fonts.ready;

    // Measure a sample character to determine the exact dimensions for the canvas.
    const charMetrics = outputCtx.measureText('@');
    const singleCharWidth = charMetrics.width;
    const singleCharHeight = fontSize; // A reasonable approximation for line height.

    outputCanvas.width = charWidth * singleCharWidth;
    outputCanvas.height = charHeight * singleCharHeight;
    
    // Prevent creating a canvas that's too large and might crash the browser.
    if (outputCanvas.width > 8192 || outputCanvas.height > 8192) {
        console.error("Resulting canvas is too large. Please increase the 'resolution' value (e.g., to 15 or 20) to reduce the output size.");
        const errorCanvas = document.createElement('canvas');
        errorCanvas.width = 400;
        errorCanvas.height = 50;
        const errCtx = errorCanvas.getContext('2d');
        errCtx.font = "16px Arial";
        errCtx.fillStyle = "red";
        errCtx.fillText("Output too large. Increase 'resolution' parameter.", 10, 30);
        return errorCanvas;
    }

    // 4. Style and fill the output canvas.
    outputCtx.font = font; // Re-apply font as context state can be reset.
    outputCtx.textBaseline = 'top';
    const bgColor = isInverted ? 'white' : 'black';
    const fgColor = isInverted ? 'black' : 'white';

    outputCtx.fillStyle = bgColor;
    outputCtx.fillRect(0, 0, outputCanvas.width, outputCanvas.height);
    outputCtx.fillStyle = fgColor;

    // 5. Iterate through the downsampled pixel data and draw characters.
    const alphabetLen = alphabet.length;
    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];

        // Calculate brightness using the standard luminosity formula.
        const brightness = (0.299 * r + 0.587 * g + 0.114 * b);

        // Invert brightness if the flag is set.
        const effectiveBrightness = isInverted ? (255 - brightness) : brightness;

        // Map the 0-255 brightness range to an index in our alphabet string.
        const charIndex = Math.floor((effectiveBrightness / 255) * (alphabetLen - 1));
        const char = alphabet.charAt(charIndex);

        // Calculate the x, y position in the character grid.
        const pixelIndex = i / 4;
        const x = (pixelIndex % charWidth);
        const y = Math.floor(pixelIndex / charWidth);

        // Draw the character onto the canvas.
        outputCtx.fillText(char, x * singleCharWidth, y * singleCharHeight);
    }

    // 6. Return the completed canvas.
    return outputCanvas;
}

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 Alphabet Translator Tool converts images into character-based representations, also known as ASCII art or character art. Users can input an image and define a set of characters from which to create the representation. The tool samples the image at a specified resolution, mapping pixel brightness to characters, producing a visually engaging output that can be used for artistic purposes, decoration, or programming projects. It allows for customization through different character sets and an option to invert brightness, offering flexibility for various creative needs.

Leave a Reply

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