Please bookmark this page to avoid losing your image tool!

Image Text Extractor And Translator

(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, sourceLang = 'eng', targetLang = 'en') {

    /**
     * Dynamically loads a script and returns a promise that resolves when the script is loaded.
     * @param {string} src - The source URL of the script to load.
     * @returns {Promise<void>}
     */
    const loadScript = (src) => {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = src;
            script.onload = resolve;
            script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
            document.head.appendChild(script);
        });
    };

    // Create a container element to display progress and results.
    const resultContainer = document.createElement('div');
    resultContainer.style.fontFamily = 'Arial, sans-serif';
    resultContainer.style.padding = '15px';
    resultContainer.style.border = '1px solid #ddd';
    resultContainer.style.borderRadius = '8px';
    resultContainer.style.backgroundColor = '#f9f9f9';
    resultContainer.style.maxWidth = (originalImg.width > 400 ? originalImg.width : 400) + 'px';
    resultContainer.style.boxSizing = 'border-box';

    const statusElement = document.createElement('p');
    statusElement.style.margin = '0 0 15px 0';
    statusElement.style.fontWeight = 'bold';
    statusElement.style.color = '#333';
    resultContainer.appendChild(statusElement);

    const extractedContainer = document.createElement('div');
    const translatedContainer = document.createElement('div');
    resultContainer.appendChild(extractedContainer);
    resultContainer.appendChild(translatedContainer);
    
    /**
     * Updates the status message displayed to the user.
     * @param {string} text - The status message to display.
     */
    const updateStatus = (text) => {
        statusElement.textContent = text;
    };

    try {
        // Step 1: Dynamically load Tesseract.js OCR library if not already available.
        updateStatus('Loading OCR engine...');
        if (typeof Tesseract === 'undefined') {
            await loadScript('https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js');
        }
        updateStatus('OCR engine loaded.');

        // Step 2: Perform Optical Character Recognition (OCR) on the image.
        const worker = await Tesseract.createWorker(sourceLang, 1, {
            logger: m => {
                if (m.status === 'recognizing text') {
                    const progress = Math.round(m.progress * 100);
                    updateStatus(`Recognizing Text: ${progress}%`);
                } else {
                    // Capitalize first letter for display
                    const statusText = m.status.charAt(0).toUpperCase() + m.status.slice(1);
                    updateStatus(`OCR Status: ${statusText}...`);
                }
            },
        });
        
        const { data: { text: extractedText } } = await worker.recognize(originalImg);
        await worker.terminate();

        // Step 3: Display the extracted text.
        extractedContainer.innerHTML = `
            <h3 style="margin-top: 15px; margin-bottom: 5px; color: #1a73e8;">Extracted Text (${sourceLang})</h3>
            <pre style="white-space: pre-wrap; word-wrap: break-word; background: #fff; padding: 10px; border: 1px solid #ccc; border-radius: 4px; min-height: 50px; font-family: monospace;">${extractedText || 'No text found.'}</pre>
        `;

        // If no text was found, we are done.
        if (!extractedText.trim()) {
             updateStatus('Completed: No text found to translate.');
             return resultContainer;
        }

        // Step 4: Translate the extracted text using a free API.
        updateStatus('Translating text...');
        // The MyMemory API uses 2-letter ISO 639-1 codes. We'll attempt to convert from Tesseract's 3-letter code.
        const sourceLang2Letter = sourceLang.substring(0, 2); 
        const apiUrl = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(extractedText)}&langpair=${sourceLang2Letter}|${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;

        // Step 5: Display the translated text.
        translatedContainer.innerHTML = `
            <h3 style="margin-top: 15px; margin-bottom: 5px; color: #188038;">Translated Text (${targetLang})</h3>
            <pre style="white-space: pre-wrap; word-wrap: break-word; background: #fff; padding: 10px; border: 1px solid #ccc; border-radius: 4px; min-height: 50px; font-family: monospace;">${translatedText}</pre>
        `;
        
        updateStatus('Completed successfully!');

    } catch (error) {
        console.error('An error occurred during image processing:', error);
        updateStatus('An error occurred.');
        const errorElement = document.createElement('p');
        errorElement.style.color = 'red';
        errorElement.style.marginTop = '10px';
        errorElement.textContent = `Error: ${error.message}`;
        resultContainer.appendChild(errorElement);
    }

    // Return the container element with all the results.
    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 Extractor and Translator is an online tool that enables users to extract text from images using Optical Character Recognition (OCR) technology and subsequently translate that text into a different language. This tool is ideal for a variety of use cases such as translating text from scanned documents, recognizing and translating text from photos of signs or menus, and converting printed material into digital formats for easier sharing and understanding. Users can upload images, specify the source and target languages, and receive the extracted and translated text in a user-friendly format.

Leave a Reply

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