Please bookmark this page to avoid losing your image tool!

Image Text Character Counter

(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.
/**
 * Performs Optical Character Recognition (OCR) on an image to extract text,
 * then counts the characters, words, and lines.
 * This function requires an internet connection to download the Tesseract.js library and language data.
 *
 * @param {Image} originalImg The original Image object to process.
 * @param {string} lang The language code for the text in the image (e.g., 'eng' for English, 'rus' for Russian, 'eng+rus' for both). Defaults to 'eng'. A full list of codes can be found in the Tesseract.js documentation.
 * @returns {Promise<HTMLDivElement>} A promise that resolves to an HTMLDivElement containing the recognized text and character count statistics.
 */
async function processImage(originalImg, lang = 'eng') {
    // Helper function to dynamically load the Tesseract.js script from a CDN.
    const loadTesseract = () => {
        return new Promise((resolve, reject) => {
            // If Tesseract is already loaded, resolve immediately.
            if (window.Tesseract) {
                return resolve();
            }
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';
            script.onload = () => resolve();
            script.onerror = () => reject(new Error('Failed to load Tesseract.js script.'));
            document.head.appendChild(script);
        });
    };

    // Create the main container element that will be returned.
    const container = document.createElement('div');
    container.style.fontFamily = 'Arial, sans-serif';
    container.style.padding = '10px';
    container.style.color = '#333';
    container.style.lineHeight = '1.5';

    // Create a status element to show progress to the user.
    const statusDiv = document.createElement('div');
    statusDiv.style.marginBottom = '15px';
    statusDiv.style.fontWeight = 'bold';
    statusDiv.style.color = '#0056b3';
    container.appendChild(statusDiv);

    try {
        statusDiv.textContent = 'Loading OCR library...';
        await loadTesseract();

        statusDiv.textContent = 'Initializing OCR engine...';
        
        // Use the simple Tesseract.recognize() method for OCR.
        // It handles worker creation and termination automatically.
        const { data: { text } } = await Tesseract.recognize(
            originalImg,
            lang,
            {
                logger: m => {
                    // The logger callback provides real-time progress updates.
                    const status = m.status.replace(/_/g, ' '); // Make status messages more readable
                    const progress = (m.progress * 100).toFixed(1);
                    statusDiv.innerHTML = `Status: <span style="text-transform: capitalize;">${status}</span>... ${progress}%`;
                }
            }
        );
        
        // Hide the status div once processing is complete.
        statusDiv.style.display = 'none';

        // --- Calculate Statistics ---
        const charCount = text.length;
        const charCountNoSpaces = text.replace(/\s/g, '').length;
        const wordCount = (text.match(/\S+/g) || []).length;
        const lineCount = text ? text.split('\n').length : 0;

        // --- Create Result Display ---

        // Heading for the recognized text section
        const textTitle = document.createElement('h3');
        textTitle.textContent = 'Recognized Text:';
        textTitle.style.margin = '10px 0 5px 0';
        container.appendChild(textTitle);
        
        // A <pre> element to display the recognized text, preserving formatting.
        const textPre = document.createElement('pre');
        textPre.textContent = text.trim() || '(No text detected)';
        textPre.style.whiteSpace = 'pre-wrap';
        textPre.style.wordWrap = 'break-word';
        textPre.style.border = '1px solid #ccc';
        textPre.style.backgroundColor = '#f9f9f9';
        textPre.style.padding = '10px';
        textPre.style.maxHeight = '300px';
        textPre.style.overflowY = 'auto';
        textPre.style.margin = '0';
        container.appendChild(textPre);

        // Heading for the statistics section
        const statsTitle = document.createElement('h3');
        statsTitle.textContent = 'Statistics:';
        statsTitle.style.margin = '20px 0 5px 0';
        container.appendChild(statsTitle);
        
        // An unordered list to display the calculated statistics.
        const statsList = document.createElement('ul');
        statsList.style.listStyleType = 'none';
        statsList.style.padding = '0';
        statsList.style.margin = '0';

        const stats = {
            'Total Characters (with spaces)': charCount,
            'Characters (no spaces)': charCountNoSpaces,
            'Words': wordCount,
            'Lines': lineCount,
        };

        for (const [key, value] of Object.entries(stats)) {
            const listItem = document.createElement('li');
            listItem.style.padding = '3px 0';
            listItem.innerHTML = `<strong style="display: inline-block; width: 220px;">${key}:</strong> ${value}`;
            statsList.appendChild(listItem);
        }
        
        container.appendChild(statsList);

    } catch (error) {
        console.error('OCR process failed:', error);
        statusDiv.textContent = `Error: ${error.message || 'An unknown error occurred during OCR.'}`;
        statusDiv.style.color = '#d9534f'; // Use a red color for errors
    }

    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 Text Character Counter is an online tool that uses Optical Character Recognition (OCR) technology to extract text from images. This tool can count the total number of characters, words, and lines present in the recognized text. It is useful for a variety of applications, such as analyzing documents, verifying text content from images, and generating statistics for text-heavy images. Users can upload images in various languages, and the tool will provide a detailed breakdown of the text and its corresponding character and word counts.

Leave a Reply

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