Please bookmark this page to avoid losing your image tool!

Image ASCII Translator

(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.
/**
 * Converts an image into an ASCII art representation on a canvas.
 *
 * @param {HTMLImageElement} originalImg The source image object.
 * @param {number} [scale=10] The size (in pixels) of each square area in the original image to be converted into a single character. Smaller values result in higher resolution and larger output.
 * @param {string} [characterSet='default'] A preset name ('default', 'detailed', 'blocks', 'binary') or a custom string of characters. Characters should be ordered from representing the least dense/darkest areas to the most dense/brightest.
 * @param {number} [invert=0] Set to 1 to invert the character map. By default (0), bright areas of the image are mapped to denser characters (e.g., '@') and dark areas to sparser characters (e.g., ' ').
 * @param {string} [backgroundColor='#000000'] The background color of the output canvas, in a CSS-compatible format.
 * @param {string} [textColor='#FFFFFF'] The color of the ASCII characters, in a CSS-compatible format.
 * @returns {Promise<HTMLCanvasElement>} A canvas element containing the generated ASCII art.
 */
async function processImage(originalImg, scale = 10, characterSet = 'default', invert = 0, backgroundColor = '#000000', textColor = '#FFFFFF') {
    // 1. Sanitize parameters
    const safeScale = Math.max(1, Number(scale) || 10);
    const shouldInvert = Number(invert) === 1;

    // 2. Define character sets
    const presets = {
        'default': ' .:-=+*#%@',
        'detailed': ' .\'`^",:;Il!i<>~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$',
        'blocks': ' ░▒▓█',
        'binary': ' #'
    };

    let charList = presets[characterSet] || characterSet;

    // By default (invert=0), the map is: bright pixel -> dense char
    // If inverted, the map becomes: bright pixel -> sparse char
    if (shouldInvert) {
        charList = charList.split('').reverse().join('');
    }
    const charCount = charList.length;

    // 3. Create a source canvas to read pixel data
    const srcCanvas = document.createElement('canvas');
    const srcCtx = srcCanvas.getContext('2d', {
        willReadFrequently: true
    });
    srcCanvas.width = originalImg.naturalWidth;
    srcCanvas.height = originalImg.naturalHeight;
    srcCtx.drawImage(originalImg, 0, 0);

    // 4. Prepare the output canvas
    const cols = Math.floor(srcCanvas.width / safeScale);
    const rows = Math.floor(srcCanvas.height / safeScale);

    // Handle cases where the image is too small for the given scale
    if (cols === 0 || rows === 0) {
        const emptyCanvas = document.createElement('canvas');
        emptyCanvas.width = 1;
        emptyCanvas.height = 1;
        return emptyCanvas;
    }

    const outputCanvas = document.createElement('canvas');
    const outputCtx = outputCanvas.getContext('2d');

    // Use scale for font size and a monospace font for grid alignment
    const fontSize = safeScale;
    outputCtx.font = `${fontSize}px monospace`;

    // Measure a character to calculate the required canvas size accurately
    const metrics = outputCtx.measureText('@'); // Use a wide character for reliable width
    const charWidth = metrics.width;
    const charHeight = fontSize; // Approximate line height

    outputCanvas.width = Math.ceil(cols * charWidth);
    outputCanvas.height = Math.ceil(rows * charHeight);

    // Re-apply settings as they are reset on canvas resize
    outputCtx.font = `${fontSize}px monospace`;
    outputCtx.textBaseline = 'top';

    // 5. Fill background and set text color
    outputCtx.fillStyle = backgroundColor;
    outputCtx.fillRect(0, 0, outputCanvas.width, outputCanvas.height);
    outputCtx.fillStyle = textColor;

    // 6. Iterate through image blocks, calculate brightness, and draw characters
    for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
            const sx = x * safeScale;
            const sy = y * safeScale;

            const imageData = srcCtx.getImageData(sx, sy, safeScale, safeScale);
            const data = imageData.data;
            let totalBrightness = 0;
            let pixelCount = 0;

            for (let i = 0; i < data.length; i += 4) {
                // Ignore fully transparent pixels to not skew the average
                if (data[i + 3] === 0) {
                    continue;
                }
                const r = data[i];
                const g = data[i + 1];
                const b = data[i + 2];
                // Luminosity formula for grayscale conversion
                const brightness = 0.299 * r + 0.587 * g + 0.114 * b;
                totalBrightness += brightness;
                pixelCount++;
            }

            // If the block was fully transparent, treat it as the darkest value
            const avgBrightness = pixelCount > 0 ? totalBrightness / pixelCount : 0;

            // Map brightness (0-255) to a character index (0 to charCount-1)
            const charIndex = Math.floor((avgBrightness / 255) * (charCount - 1));
            const char = charList[charIndex];

            if (char) {
                outputCtx.fillText(char, x * charWidth, y * charHeight);
            }
        }
    }

    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

Image ASCII Translator is a versatile online tool that converts standard images into artistic representations using ASCII characters. It allows users to adjust the scale of the output for different resolutions and choose from various character sets that can provide different styles of ASCII art. This tool is useful for creating unique visual content for social media, enhancing text documents with interesting graphics, or simply having fun with image manipulations. Users can also customize the text and background colors, making it a flexible option for artistic expression.

Leave a Reply

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