Please bookmark this page to avoid losing your image tool!

Image Text Translator API

(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 OCR on an image to extract text and then translates it to a specified language.
 * This function uses Tesseract.js for OCR and the MyMemory API for translation.
 *
 * @param {Image} originalImg The original image object to process.
 * @param {string} sourceLang The 2-letter language code (ISO 639-1) of the text in the image (e.g., 'en', 'ru'). Defaults to 'en'.
 * @param {string} targetLang The 2-letter language code (ISO 639-1) to translate the text into (e.g., 'es', 'fr'). Defaults to 'ru'.
 * @returns {Promise<HTMLDivElement>} A promise that resolves to a div element containing the extracted and translated text.
 */
async function processImage(originalImg, sourceLang = 'en', targetLang = 'ru') {
    // 1. Create the main container element to return
    const resultContainer = document.createElement('div');
    resultContainer.style.fontFamily = 'Arial, sans-serif';
    resultContainer.style.padding = '10px';
    resultContainer.style.maxWidth = '100%';
    resultContainer.style.boxSizing = 'border-box';

    // 2. Create a status element for progress updates
    const statusElement = document.createElement('p');
    statusElement.style.margin = '0 0 10px 0';
    statusElement.style.color = '#333';
    resultContainer.appendChild(statusElement);

    const setStatus = (message) => {
        statusElement.textContent = message;
    };

    try {
        // 3. Dynamically load the Tesseract.js library
        setStatus('Loading OCR engine...');
        const TESSERACT_CDN = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';

        if (typeof Tesseract === 'undefined') {
            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 library from CDN.'));
                document.head.appendChild(script);
            });
        }
        setStatus('OCR engine loaded.');

        // 4. Map 2-letter language codes to Tesseract's 3-letter codes
        const langMap = {
            'en': 'eng', 'ru': 'rus', 'fr': 'fra', 'de': 'deu', 'es': 'spa',
            'it': 'ita', 'pt': 'por', 'zh': 'chi_sim', 'ja': 'jpn', 'ko': 'kor', 'ar': 'ara'
        };
        const tesseractLang = langMap[sourceLang.toLowerCase()] || sourceLang.toLowerCase();

        // 5. Perform OCR using Tesseract.js
        setStatus('Initializing OCR worker...');
        // Create a canvas to pass to Tesseract, which can sometimes be more reliable than an Image element
        const canvas = document.createElement('canvas');
        canvas.width = originalImg.naturalWidth;
        canvas.height = originalImg.naturalHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(originalImg, 0, 0);

        const worker = await Tesseract.createWorker(tesseractLang, 1, {
            logger: m => {
                if (m.status === 'recognizing text') {
                    setStatus(`Recognizing text... (${(m.progress * 100).toFixed(0)}%)`);
                } else {
                     setStatus(`OCR Worker: ${m.status}`);
                }
            }
        });

        const { data: { text } } = await worker.recognize(canvas);
        await worker.terminate();
        setStatus('Text recognition complete.');

        // Display the extracted text
        const extractedTitle = document.createElement('h3');
        extractedTitle.textContent = 'Extracted Text';
        extractedTitle.style.marginTop = '10px';
        extractedTitle.style.marginBottom = '5px';
        resultContainer.appendChild(extractedTitle);

        const extractedTextElement = document.createElement('pre');
        extractedTextElement.textContent = text || '(No text detected)';
        extractedTextElement.style.cssText = 'white-space: pre-wrap; word-wrap: break-word; border: 1px solid #ccc; padding: 10px; background-color: #f9f9f9; border-radius: 4px;';
        resultContainer.appendChild(extractedTextElement);

        if (!text.trim()) {
            setStatus('No text found to translate.');
            return resultContainer;
        }

        // 6. Translate the extracted text using MyMemory API
        setStatus('Translating text...');
        const apiUrl = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${sourceLang}|${targetLang}`;

        const response = await fetch(apiUrl);
        if (!response.ok) {
            throw new Error(`Translation API request failed with status ${response.status}`);
        }
        const data = await response.json();

        if (data.responseStatus !== 200) {
            throw new Error(`Translation failed: ${data.responseDetails}`);
        }
        const translatedText = data.responseData.translatedText;

        // Display the translated text
        const translatedTitle = document.createElement('h3');
        translatedTitle.textContent = `Translated Text (${targetLang.toUpperCase()})`;
        translatedTitle.style.marginTop = '20px';
        translatedTitle.style.marginBottom = '5px';
        resultContainer.appendChild(translatedTitle);

        const translatedTextElement = document.createElement('pre');
        translatedTextElement.textContent = translatedText;
        translatedTextElement.style.cssText = 'white-space: pre-wrap; word-wrap: break-word; border: 1px solid #ccc; padding: 10px; background-color: #eaf2ff; border-radius: 4px;';
        resultContainer.appendChild(translatedTextElement);

        setStatus('Translation complete.');

    } catch (error) {
        console.error('An error occurred during image processing:', error);
        setStatus(`Error: ${error.message}`);
        statusElement.style.color = 'red';
    }

    // 7. Return the final element containing all 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 Translator API is a tool that allows users to extract text from images using Optical Character Recognition (OCR) and then translate the extracted text into a specified language. This tool is useful for a variety of applications such as translating text from signs, documents, or images of printed materials, making it convenient for travelers, students, and professionals who need to understand foreign language texts. With support for multiple languages, the API enables seamless communication and comprehension of written content across language barriers.

Leave a Reply

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