Please bookmark this page to avoid losing your image tool!

Image To ASCII Art 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.
/**
 * Converts an image to ASCII art.
 *
 * @param {Image} originalImg The source Image object (must be loaded).
 * @param {string} [charset=' .:-=+*#%@'] The character set to use, ordered from lightest to darkest pixel representation.
 * @param {number} [maxWidth=80] The maximum width of the generated ASCII art in characters. Height is scaled proportionally.
 * @returns {HTMLElement} A <pre> element containing the ASCII art.
 */
async function processImage(originalImg, charset = ' .:-=+*#%@', maxWidth = 80) {
    // Ensure charset is a non-empty string
    if (typeof charset !== 'string' || charset.length === 0) {
        console.warn("Invalid charset provided, using default.");
        charset = ' .:-=+*#%@'; // Light to dark
    }
    // Ensure maxWidth is a positive number
    if (typeof maxWidth !== 'number' || !Number.isFinite(maxWidth) || maxWidth <= 0) {
        console.warn("Invalid maxWidth provided, using default.");
        maxWidth = 80;
    }

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d', {
        // Optimize for frequent reads if available, though not strictly necessary here unless processing many frames/images
        willReadFrequently: true
    });

    // --- Calculate dimensions ---
    // Determine the scaling factor based on maxWidth
    const originalWidth = originalImg.naturalWidth || originalImg.width;
    const originalHeight = originalImg.naturalHeight || originalImg.height;

    if (originalWidth === 0 || originalHeight === 0) {
        console.error("Invalid image dimensions (0).");
        const errorPre = document.createElement('pre');
        errorPre.textContent = "Error: Image has zero width or height.";
        errorPre.style.color = 'red';
        return errorPre;
    }

    let targetWidth = Math.min(maxWidth, originalWidth);
    // Calculate corresponding height based on aspect ratio
    const aspectRatio = originalHeight / originalWidth;
    // Adjust height to somewhat compensate for aspect ratio of typical characters (taller than wide)
    // A factor of 0.5-0.6 is common. This makes the output less "stretched" vertically.
    const characterAspectRatioFactor = 0.55;
    let targetHeight = Math.round(targetWidth * aspectRatio * characterAspectRatioFactor);

    // Ensure dimensions are at least 1x1
    targetWidth = Math.max(1, Math.floor(targetWidth));
    targetHeight = Math.max(1, Math.floor(targetHeight));

    canvas.width = targetWidth;
    canvas.height = targetHeight;

    // --- Draw image and get pixel data ---
    // Draw the image onto the canvas, scaling it down
    ctx.drawImage(originalImg, 0, 0, targetWidth, targetHeight);

    let imageData;
    try {
        // Get the pixel data from the canvas
        imageData = ctx.getImageData(0, 0, targetWidth, targetHeight);
    } catch (e) {
        console.error("Error getting image data:", e);
        const errorPre = document.createElement('pre');
        errorPre.textContent = `Error: Could not process image.\n${e.message}\n(This often happens if the image is from a different domain and lacks CORS headers.)`;
        errorPre.style.color = 'red';
        errorPre.style.whiteSpace = 'pre-wrap'; // Wrap error message text
        return errorPre;
    }
    const data = imageData.data; // data is a Uint8ClampedArray: [R, G, B, A, R, G, B, A, ...]

    // --- Generate ASCII string ---
    const characters = charset.split(''); // Convert charset string to array
    const numChars = characters.length;
    let asciiArt = '';

    for (let y = 0; y < targetHeight; y++) {
        for (let x = 0; x < targetWidth; x++) {
            // Calculate the index for the current pixel in the data array
            const offset = (y * targetWidth + x) * 4;
            const r = data[offset];
            const g = data[offset + 1];
            const b = data[offset + 2];
            // data[offset + 3] is the alpha value, ignored here but could be used

            // Calculate luminance (perceived brightness) - more accurate than simple average
            // Formula: 0.2126*R + 0.7152*G + 0.0722*B
            const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b; // Value between 0 and 255

            // Normalize luminance to a range of 0 to 1
            const normalizedLuminance = luminance / 255;

            // Map the normalized luminance to an index in the character set
            // Clamp the index to ensure it's within the bounds [0, numChars - 1]
            const charIndex = Math.min(Math.floor(normalizedLuminance * numChars), numChars - 1);

            // Append the corresponding character to the result string
            asciiArt += characters[charIndex];
        }
        // Add a newline character at the end of each row
        asciiArt += '\n';
    }

    // --- Create output element ---
    const preElement = document.createElement('pre');
    // Apply styles for proper display of ASCII art
    preElement.style.fontFamily = 'monospace, "Courier New", Courier'; // Crucial for alignment
    preElement.style.fontSize = '10px'; // Smaller font size often looks better
    preElement.style.lineHeight = '1.0'; // Adjust line height for density
    preElement.style.letterSpacing = '0';   // Adjust letter spacing if needed
    preElement.style.margin = '0';          // Remove default margins
    preElement.style.whiteSpace = 'pre';    // Preserve whitespace and line breaks
    preElement.style.overflow = 'auto';   // Add scrollbars if content overflows
    preElement.textContent = asciiArt;

    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 ASCII Art Converter allows users to transform images into ASCII art representations. By converting images pixel by pixel into a range of ASCII characters (using a specified character set), this tool creates a text-based version of the original image. It is useful for artistic purposes, shareable content for social media, or simply to enjoy an alternative representation of images. Users can adjust the width of the generated ASCII art and specify their preferred characters for a customized output.

Leave a Reply

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