Please bookmark this page to avoid losing your image tool!

Image Name Translator And Code Scene Identifier 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.
/**
 * Analyzes an image to determine if it is a screenshot of a code editor scene.
 * It uses heuristics based on color complexity and the presence of horizontal text-like lines.
 * The "Name Translator" aspect is interpreted as providing a descriptive classification of the image content.
 *
 * @param {Image} originalImg The original Image object to process.
 * @param {number} confidenceThreshold A number between 0 and 100. If the calculated confidence score
 * is above this threshold, the image is classified as a code scene. Defaults to 50.
 * @returns {HTMLElement} A DIV element containing the original image and the analysis result.
 */
function processImage(originalImg, confidenceThreshold = 50) {

    // --- Helper Functions ---

    /**
     * Calculates the perceived brightness of an RGB color.
     * @param {number} r Red channel (0-255)
     * @param {number} g Green channel (0-255)
     * @param {number} b Blue channel (0-255)
     * @returns {number} Brightness value (0-255)
     */
    const getBrightness = (r, g, b) => (r * 299 + g * 587 + b * 114) / 1000;

    /**
     * Calculates the variance of a set of numbers.
     * @param {number[]} arr An array of numbers.
     * @returns {number} The variance of the numbers.
     */
    const getVariance = (arr) => {
        if (arr.length < 2) return 0;
        const mean = arr.reduce((a, b) => a + b, 0) / arr.length;
        const squareDiffs = arr.map(value => (value - mean) ** 2);
        return squareDiffs.reduce((a, b) => a + b, 0) / arr.length;
    };

    // 1. Setup Canvas for analysis
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d', {
        willReadFrequently: true
    });

    // Downscale large images for better performance during analysis
    const MAX_ANALYSIS_WIDTH = 400;
    const scale = originalImg.width > MAX_ANALYSIS_WIDTH ? MAX_ANALYSIS_WIDTH / originalImg.width : 1;
    const width = Math.round(originalImg.width * scale);
    const height = Math.round(originalImg.height * scale);
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(originalImg, 0, 0, width, height);

    // 2. Get Pixel Data from the canvas
    let imageData;
    try {
        imageData = ctx.getImageData(0, 0, width, height);
    } catch (e) {
        // Handle potential CORS security errors if the image is from another origin
        console.error("Could not get image data:", e);
        const errorDiv = document.createElement('div');
        errorDiv.textContent = 'Error: Cannot process this image due to security restrictions (cross-origin issues).';
        errorDiv.style.color = 'red';
        errorDiv.style.padding = '20px';
        return errorDiv;
    }
    const data = imageData.data;

    // --- Heuristic Analysis ---
    let score = 0;
    const analysisDetails = {
        theme: 'Unknown',
        uniqueColors: 0,
        highVarianceRows: 0,
    };

    // 3a. Color Complexity Analysis
    // Code screenshots typically have a limited, distinct color palette compared to photos.
    const colorCounts = new Map();
    const quantizeFactor = 16; // Group similar colors together
    for (let i = 0; i < data.length; i += 4) {
        const r = Math.round(data[i] / quantizeFactor) * quantizeFactor;
        const g = Math.round(data[i + 1] / quantizeFactor) * quantizeFactor;
        const b = Math.round(data[i + 2] / quantizeFactor) * quantizeFactor;
        const colorKey = `${r},${g},${b}`;
        colorCounts.set(colorKey, (colorCounts.get(colorKey) || 0) + 1);
    }

    const sortedColors = Array.from(colorCounts.entries()).sort((a, b) => b[1] - a[1]);
    analysisDetails.uniqueColors = sortedColors.length;

    // Score based on color complexity. Fewer unique colors suggest a synthetic image.
    const colorComplexityScore = Math.max(0, 50 - analysisDetails.uniqueColors * 0.5);
    score += colorComplexityScore;

    // Determine theme (light/dark) from the most dominant color (likely the background).
    if (sortedColors.length > 0) {
        const bgColorRgb = sortedColors[0][0].split(',').map(Number);
        const brightness = getBrightness(bgColorRgb[0], bgColorRgb[1], bgColorRgb[2]);
        analysisDetails.theme = brightness < 128 ? 'Dark' : 'Light';
    }

    // 3b. Line Structure Analysis
    // Code is organized in horizontal lines. This creates high variance in pixel brightness across rows.
    const grayscale = new Uint8ClampedArray(width * height);
    for (let i = 0, j = 0; i < data.length; i += 4, j++) {
        grayscale[j] = getBrightness(data[i], data[i + 1], data[i + 2]);
    }

    let highVarianceRowCount = 0;
    const varianceThreshold = 500; // An empirical value for what constitutes a "text-like" row.

    for (let y = 0; y < height; y++) {
        const row = Array.from(grayscale.subarray(y * width, (y + 1) * width));
        const variance = getVariance(row);
        if (variance > varianceThreshold) {
            highVarianceRowCount++;
        }
    }
    analysisDetails.highVarianceRows = highVarianceRowCount;

    // Score based on the proportion of rows that look like lines of text.
    const lineStructureRatio = highVarianceRowCount / height;
    let lineStructureScore = 0;
    if (lineStructureRatio > 0.2) { // Ignore images with very few structured lines.
        lineStructureScore = lineStructureRatio * 50;
    }
    score += lineStructureScore;

    // Normalize final score to be within 0-100 range.
    score = Math.min(100, Math.max(0, score));

    // 4. Final Decision
    const isCodeScene = score >= confidenceThreshold;

    // 5. Generate Output Element
    const container = document.createElement('div');
    container.style.fontFamily = 'Arial, sans-serif';
    container.style.textAlign = 'center';
    container.style.maxWidth = '600px';
    container.style.margin = 'auto';

    const resultCanvas = document.createElement('canvas');
    resultCanvas.width = originalImg.width;
    resultCanvas.height = originalImg.height;
    resultCanvas.getContext('2d').drawImage(originalImg, 0, 0);
    resultCanvas.style.maxWidth = '100%';
    resultCanvas.style.height = 'auto';
    resultCanvas.style.border = '1px solid #ccc';
    resultCanvas.style.borderRadius = '4px';
    resultCanvas.style.marginBottom = '15px';

    const description = document.createElement('p');
    description.style.margin = '0';
    description.style.fontSize = '1.1em';
    description.style.fontWeight = 'bold';

    const details = document.createElement('p');
    details.style.margin = '5px 0 0 0';
    details.style.fontSize = '0.9em';
    details.style.color = '#555';

    if (isCodeScene) {
        description.textContent = `Result: Probable Code Screenshot`;
        description.style.color = '#28a745'; // Green
        details.textContent = `Confidence: ${score.toFixed(0)}%. Detected Theme: ${analysisDetails.theme}.`;
    } else {
        description.textContent = `Result: Unlikely to be a Code Screenshot`;
        description.style.color = '#fd7e14'; // Orange
        details.textContent = `Confidence: ${score.toFixed(0)}%. Image appears to be a general photograph or graphic.`;
    }

    container.appendChild(resultCanvas);
    container.appendChild(description);
    container.appendChild(details);

    return container;
}

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 Name Translator And Code Scene Identifier Tool analyzes images to determine whether they depict a screenshot from a code editor. By evaluating color complexity and the presence of structured text-like lines, the tool provides a confidence score and identifies the likely theme of the image (light or dark). This tool is useful for developers and educators who want to quickly assess whether an image contains programming code, which can aid in documentation, highlighting coding techniques, or sharing coding snippets.

Leave a Reply

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