Please bookmark this page to avoid losing your image tool!

Image Text Translator From Alphabet In Photo

(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.
/**
 * Recognizes text from an image using OCR and provides a link to translate it.
 * This function uses the Tesseract.js library, which is loaded dynamically.
 * Note: OCR is a computationally intensive process and may be slow on user devices.
 *
 * @param {Image} originalImg The original javascript Image object to process.
 * @param {string} sourceLang The 3-letter ISO 639-2 language code of the text in the image (e.g., 'eng', 'rus', 'deu'). Default is 'eng'. A list can be found here: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-v4.0.0.html
 * @param {string} targetLang The 3-letter ISO 639-2 language code to translate the text into. Default is 'eng'.
 * @returns {Promise<HTMLDivElement>} A promise that resolves with an HTML div element containing the recognized text, confidence score, and a translation link.
 */
async function processImage(originalImg, sourceLang = 'eng', targetLang = 'eng') {
    // 1. Create a container for the output and progress updates
    const container = document.createElement('div');
    const statusElement = document.createElement('p');
    container.appendChild(statusElement);

    const updateStatus = (message) => {
        statusElement.textContent = message;
        statusElement.style.fontFamily = 'Arial, sans-serif';
    };

    // 2. Dynamically load Tesseract.js if it's not already available
    const TESSERACT_CDN = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';
    if (typeof Tesseract === 'undefined') {
        updateStatus('Loading OCR engine...');
        try {
            await new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = TESSERACT_CDN;
                script.onload = resolve;
                script.onerror = () => reject(new Error('Failed to load Tesseract.js script.'));
                document.head.appendChild(script);
            });
        } catch (error) {
            updateStatus(error.message);
            statusElement.style.color = 'red';
            return container;
        }
    }

    // 3. Perform OCR
    let worker;
    try {
        updateStatus('Initializing OCR worker...');
        // Create a worker to process the image in a separate thread
        worker = await Tesseract.createWorker({
            logger: m => {
                if (m.status === 'recognizing text') {
                    const progress = m.progress ? ` ${Math.round(m.progress * 100)}%` : '';
                    updateStatus(`Recognizing Text...${progress}`);
                } else {
                    const formattedStatus = m.status.charAt(0).toUpperCase() + m.status.slice(1);
                    updateStatus(`${formattedStatus}...`);
                }
            },
        });

        // Load the specified language model
        await worker.loadLanguage(sourceLang);
        await worker.initialize(sourceLang);

        // Recognize text from the image
        const {
            data: {
                text,
                confidence
            }
        } = await worker.recognize(originalImg);

        // 4. Create the result element
        const resultContainer = document.createElement('div');
        resultContainer.style.fontFamily = 'Arial, sans-serif';

        const recognizedTitle = document.createElement('h3');
        recognizedTitle.textContent = 'Recognized Text';
        resultContainer.appendChild(recognizedTitle);

        const confidenceElement = document.createElement('p');
        confidenceElement.textContent = `Confidence: ${confidence.toFixed(2)}%`;
        confidenceElement.style.fontFamily = 'monospace';
        confidenceElement.style.color = '#555';
        resultContainer.appendChild(confidenceElement);

        const textElement = document.createElement('pre');
        textElement.textContent = text || '[No text recognized]';
        textElement.style.padding = '10px';
        textElement.style.border = '1px solid #ccc';
        textElement.style.borderRadius = '4px';
        textElement.style.backgroundColor = '#f9f9f9';
        textElement.style.whiteSpace = 'pre-wrap';
        textElement.style.wordBreak = 'break-word';
        resultContainer.appendChild(textElement);

        // 5. Add translation link if source and target languages are different
        if (sourceLang !== targetLang && text.trim().length > 0) {
            const translationTitle = document.createElement('h3');
            translationTitle.textContent = 'Translation';
            translationTitle.style.marginTop = '20px';
            resultContainer.appendChild(translationTitle);

            const translateLink = document.createElement('a');
            // Google Translate uses 2-letter codes, Tesseract uses 3. We'll slice them.
            const sourceCode = sourceLang.substring(0, 2);
            const targetCode = targetLang.substring(0, 2);
            const googleTranslateUrl = `https://translate.google.com/?sl=${sourceCode}&tl=${targetCode}&text=${encodeURIComponent(text)}&op=translate`;
            
            translateLink.href = googleTranslateUrl;
            translateLink.textContent = `Translate text from ${sourceLang} to ${targetLang} via Google Translate`;
            translateLink.target = '_blank'; // Open in a new tab
            translateLink.rel = 'noopener noreferrer';
            resultContainer.appendChild(translateLink);
        }

        // Replace status element with the final results
        container.innerHTML = '';
        container.appendChild(resultContainer);
        return container;

    } catch (error) {
        console.error('OCR Error:', error);
        updateStatus(`An error occurred: ${error.message}`);
        statusElement.style.color = 'red';
        return container;
    } finally {
        // Terminate the worker to free up resources
        if (worker) {
            await worker.terminate();
            console.log('Tesseract worker terminated.');
        }
    }
}

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 Translator from Alphabet in Photo tool allows users to extract text from images using Optical Character Recognition (OCR) technology. By simply uploading an image, the tool can recognize the text contained within it and display the results, including a confidence score for the accuracy of the recognition. Additionally, if the recognized text is in a different language than desired, users can obtain a translation via a provided link to Google Translate. This tool is useful for translating text from images in various contexts, such as reading foreign signs, menus, documents, and more.

Leave a Reply

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