Please bookmark this page to avoid losing your image tool!

Image Language Translator And Code Generator

(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.
/**
 * Extracts text from an image using OCR, translates it to a target language,
 * and generates an HTML element displaying the results.
 * 
 * This function dynamically loads the Tesseract.js library for Optical Character Recognition (OCR).
 * It then uses a free public API (MyMemory) for translation.
 *
 * @param {HTMLImageElement} originalImg The original image object to process.
 * @param {string} [targetLang='en'] The two-letter ISO 639-1 code for the language to translate the text into (e.g., 'es', 'fr', 'de').
 * @param {string} [ocrLang='eng'] The Tesseract.js language code for the text in the image (e.g., 'eng', 'fra', 'spa').
 * @returns {Promise<HTMLDivElement>} A promise that resolves to a DIV element containing the original image, extracted text, and translated text.
 */
async function processImage(originalImg, targetLang = 'en', ocrLang = 'eng') {
    // Create the main container for the output
    const container = document.createElement('div');
    container.style.fontFamily = 'Arial, sans-serif';
    container.style.padding = '15px';
    container.style.border = '1px solid #ddd';
    container.style.borderRadius = '8px';
    container.style.maxWidth = '100%';
    container.style.boxSizing = 'border-box';
    container.style.lineHeight = '1.6';

    // Create a status element to show progress to the user
    const statusDiv = document.createElement('p');
    statusDiv.textContent = 'Initializing...';
    statusDiv.style.padding = '10px';
    statusDiv.style.background = '#f0f0f0';
    statusDiv.style.border = '1px solid #ccc';
    container.appendChild(statusDiv);

    try {
        // 1. Dynamically load Tesseract.js library if it's not already available
        if (typeof Tesseract === 'undefined') {
            statusDiv.textContent = 'Loading OCR engine (Tesseract.js)...';
            await new Promise((resolve, reject) => {
                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;
                document.head.appendChild(script);
            });
        }

        // 2. Perform OCR on the image
        statusDiv.textContent = 'Creating OCR worker...';
        const worker = await Tesseract.createWorker({
            logger: m => {
                if (m.status === 'recognizing text') {
                    statusDiv.innerHTML = `Recognizing Text: ${Math.round(m.progress * 100)}%`;
                } else {
                    const statusText = m.status.charAt(0).toUpperCase() + m.status.slice(1);
                    statusDiv.textContent = `Status: ${statusText}...`;
                }
            },
        });

        await worker.loadLanguage(ocrLang);
        await worker.initialize(ocrLang);
        const { data: { text: extractedText } } = await worker.recognize(originalImg);
        await worker.terminate();

        // 3. Generate HTML to display results
        container.innerHTML = ''; // Clear status messages

        const addSection = (title, contentElement) => {
            const titleElement = document.createElement('h3');
            titleElement.textContent = title;
            titleElement.style.marginTop = '20px';
            titleElement.style.marginBottom = '8px';
            titleElement.style.borderBottom = '1px solid #eee';
            titleElement.style.paddingBottom = '4px';
            container.appendChild(titleElement);
            container.appendChild(contentElement);
        };

        // Display original image
        const imgElement = document.createElement('img');
        imgElement.src = originalImg.src;
        imgElement.style.maxWidth = '100%';
        imgElement.style.height = 'auto';
        imgElement.style.borderRadius = '4px';
        addSection('Original Image:', imgElement);

        // Display extracted text
        const extractedPre = document.createElement('pre');
        extractedPre.textContent = extractedText.trim() || '(No text detected)';
        extractedPre.style.whiteSpace = 'pre-wrap';
        extractedPre.style.wordBreak = 'break-word';
        extractedPre.style.background = '#f4f4f4';
        extractedPre.style.padding = '10px';
        extractedPre.style.border = '1px solid #ccc';
        extractedPre.style.borderRadius = '4px';
        addSection(`Extracted Text (Language: ${ocrLang}):`, extractedPre);

        // 4. Translate the extracted text if any was found
        if (extractedText.trim()) {
            const translatedPre = document.createElement('pre');
            translatedPre.textContent = 'Translating...';
            translatedPre.style.whiteSpace = 'pre-wrap';
            translatedPre.style.wordBreak = 'break-word';
            translatedPre.style.background = '#e8f4ff';
            translatedPre.style.padding = '10px';
            translatedPre.style.border = '1px solid #add8e6';
            translatedPre.style.borderRadius = '4px';
            addSection(`Translated Text (to ${targetLang.toUpperCase()}):`, translatedPre);

            try {
                // Map Tesseract's lang codes (ISO 639-2) to translation API's codes (ISO 639-1)
                const langMap = {
                    'eng': 'en', 'fra': 'fr', 'spa': 'es', 'deu': 'de', 'ita': 'it', 
                    'por': 'pt', 'rus': 'ru', 'jpn': 'ja', 'chi_sim': 'zh-CN', 'chi_tra': 'zh-TW', 'kor': 'ko'
                };
                const sourceLang = langMap[ocrLang] || ocrLang.substring(0, 2);

                const apiUrl = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(extractedText)}&langpair=${sourceLang}|${targetLang}`;
                const response = await fetch(apiUrl);
                if (!response.ok) throw new Error(`API request failed with status ${response.status}`);
                
                const data = await response.json();
                if (data.responseStatus !== 200) throw new Error(data.responseDetails);
                
                translatedPre.textContent = data.responseData.translatedText;

            } catch (translateError) {
                console.error('Translation error:', translateError);
                translatedPre.textContent = `Could not translate text: ${translateError.message}`;
                translatedPre.style.color = '#c00';
            }
        }
        return container;

    } catch (error) {
        console.error('An error occurred during image processing:', error);
        statusDiv.textContent = `Error: ${error.message}`;
        statusDiv.style.color = '#c00'; // red
        statusDiv.style.background = '#fff0f0';
        statusDiv.style.border = '1px solid #c00';
        return container; // Return the container with the error message
    }
}

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 Language Translator And Code Generator tool enables users to extract text from images using Optical Character Recognition (OCR) and translates the extracted text into a specified target language. This tool is beneficial for converting text from printed materials such as signs, documents, or books into editable and translatable text, facilitating communication in different languages. It is particularly useful for travelers, students, or anyone needing to translate information from visual sources, making access to content in various languages more seamless.

Leave a Reply

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