Please bookmark this page to avoid losing your image tool!

Image Text Translator From 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.
async function processImage(originalImg, ocrLang = 'eng', targetLang = 'en') {
    /**
     * Extracts text from an image using Tesseract.js OCR and translates it using a public API.
     * @param {Image} originalImg - The source JavaScript Image object.
     * @param {string} ocrLang - Language for Tesseract.js OCR. Must be a Tesseract language code (e.g., 'eng', 'rus', 'jpn').
     * @param {string} targetLang - Target language for translation. Must be an ISO 639-1 code (e.g., 'en', 'ru', 'ja').
     * @returns {Promise<HTMLElement>} A promise that resolves to a div element containing the progress and the final results.
     */

    // Helper function to safely display text in HTML, preventing XSS
    const escapeHtml = (unsafeText) => {
        const div = document.createElement('div');
        div.innerText = unsafeText;
        return div.innerHTML;
    };

    // Create a container element to display progress and final results
    const resultContainer = document.createElement('div');
    resultContainer.style.fontFamily = 'Arial, sans-serif';
    resultContainer.style.padding = '15px';
    resultContainer.style.border = '1px solid #ccc';
    resultContainer.style.borderRadius = '8px';
    resultContainer.style.backgroundColor = '#f9f9f9';
    resultContainer.style.maxWidth = '100%';
    resultContainer.style.boxSizing = 'border-box';
    resultContainer.innerHTML = `<p>Initializing...</p>`;

    const updateStatus = (message) => {
        resultContainer.innerHTML = `<p style="margin:0;">${escapeHtml(message)}</p>`;
    };
    
    const tesseractUrl = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';

    // 1. Dynamically load the Tesseract.js library if it's not already loaded
    if (typeof Tesseract === 'undefined') {
        updateStatus('Loading OCR library...');
        try {
            await new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = tesseractUrl;
                script.onload = resolve;
                script.onerror = () => reject(new Error('Failed to load Tesseract.js script.'));
                document.head.appendChild(script);
            });
        } catch (error) {
            updateStatus(`Error: ${error.message}`);
            console.error(error);
            return resultContainer;
        }
    }

    let worker;
    try {
        // 2. Initialize the Tesseract worker with a logger to show progress
        const logger = (m) => {
            const progress = m.progress ? ` ${Math.round(m.progress * 100)}%` : '';
            let statusText = m.status.replace(/_/g, ' '); // e.g., 'recognizing_text' -> 'recognizing text'
            statusText = statusText.charAt(0).toUpperCase() + statusText.slice(1);
            updateStatus(`${statusText}...${progress}`);
        };
        worker = await Tesseract.createWorker({ logger });

        await worker.loadLanguage(ocrLang);
        await worker.initialize(ocrLang);

        // 3. Perform OCR on the image
        const { data: { text } } = await worker.recognize(originalImg);
        
        await worker.terminate(); // Terminate worker as soon as OCR is done
        worker = null; // Prevent it from being terminated again in 'finally'

        if (!text || text.trim() === "") {
            updateStatus('No text found in the image.');
            return resultContainer;
        }

        // 4. Translate the extracted text using a free public API
        updateStatus('Translating text...');
        
        const langMap = {
            'eng': 'en', 'rus': 'ru', 'deu': 'de', 'fra': 'fr', 'spa': 'es', 'ita': 'it', 
            'jpn': 'ja', 'kor': 'ko', 'chi_sim': 'zh-CN', 'chi_tra': 'zh-TW', 'por': 'pt', 
            'ara': 'ar', 'hin': 'hi'
        };
        const sourceLangForApi = langMap[ocrLang] || ocrLang.substring(0, 2);

        const apiUrl = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${sourceLangForApi}|${targetLang}`;
        
        const response = await fetch(apiUrl);
        if (!response.ok) {
            throw new Error(`Translation API request failed with status: ${response.status}`);
        }
        const translationData = await response.json();

        if (translationData.responseStatus !== 200) {
            throw new Error(`Translation API error: ${translationData.responseDetails}`);
        }
        
        const translatedText = translationData.responseData.translatedText;
        
        // 5. Display the original and translated text
        resultContainer.innerHTML = `
            <div style="margin-bottom: 15px;">
                <h4 style="margin: 0 0 5px 0; border-bottom: 1px solid #ddd; padding-bottom: 5px;">Detected Text (${ocrLang})</h4>
                <pre style="white-space: pre-wrap; word-wrap: break-word; background: #fff; padding: 10px; border: 1px solid #ddd; border-radius: 4px; max-height: 200px; overflow-y: auto;">${escapeHtml(text)}</pre>
            </div>
            <div>
                <h4 style="margin: 0 0 5px 0; border-bottom: 1px solid #ddd; padding-bottom: 5px;">Translated Text (${targetLang})</h4>
                <pre style="white-space: pre-wrap; word-wrap: break-word; background: #eef8ff; padding: 10px; border: 1px solid #cce4f6; border-radius: 4px; max-height: 200px; overflow-y: auto;">${escapeHtml(translatedText)}</pre>
            </div>
        `;

    } catch (error) {
        console.error('An error occurred during image processing:', error);
        updateStatus(`An error occurred: ${error.message}`);
    } finally {
        if (worker) {
            await worker.terminate();
        }
    }

    return resultContainer;
}

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 Photo’ is a web tool that allows users to extract text from images and translate it into different languages. Using Optical Character Recognition (OCR) technology, it can recognize text in various languages and provide translations in the desired target language. This tool is useful for travelers who need translations of signs or documents, students studying foreign languages, and anyone looking to understand written text in images. Simply upload an image, select the original text language, and choose a target language for translation.

Leave a Reply

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