Please bookmark this page to avoid losing your image tool!

Image API Detector And Translator For Alphabet

(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.
/**
 * Detects text in an image using Tesseract.js (OCR) and translates it using the MyMemory API.
 * This function dynamically loads the Tesseract.js library.
 *
 * @param {Image} originalImg The original javascript Image object to process.
 * @param {string} sourceLang The 3-letter language code for Tesseract.js to detect (e.g., 'eng', 'rus', 'deu'). Default is 'eng'.
 * @param {string} targetLang The 2-letter language code for the translation target (e.g., 'ru', 'de', 'fr'). Default is 'rus'.
 * @returns {Promise<HTMLDivElement>} A promise that resolves to a div element containing the detected text and its translation.
 */
async function processImage(originalImg, sourceLang = 'eng', targetLang = 'rus') {
    // Create a container for the output
    const container = document.createElement('div');
    container.style.fontFamily = 'Arial, sans-serif';
    container.style.padding = '10px';
    container.style.border = '1px solid #ccc';
    container.style.borderRadius = '5px';
    container.style.maxWidth = `${originalImg.width}px`;
    container.style.boxSizing = 'border-box';

    const statusDiv = document.createElement('div');
    container.appendChild(statusDiv);

    // Helper function to update status display
    const updateStatus = (message) => {
        statusDiv.innerHTML = `<p style="margin: 5px 0; color: #555;"><em>${message}</em></p>`;
    };

    // 1. Dynamically load Tesseract.js library from a CDN
    const loadTesseract = () => {
        return new Promise((resolve, reject) => {
            // Check if the script is already loaded
            if (window.Tesseract) {
                return resolve(window.Tesseract);
            }
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';
            script.onload = () => resolve(window.Tesseract);
            script.onerror = () => reject(new Error('Failed to load Tesseract.js script.'));
            document.head.appendChild(script);
        });
    };

    try {
        updateStatus('Loading OCR engine...');
        const Tesseract = await loadTesseract();

        // 2. Perform OCR to detect text in the image
        updateStatus('Initializing OCR...');
        const {
            data: {
                text
            }
        } = await Tesseract.recognize(
            originalImg,
            sourceLang, {
                logger: m => {
                    // Update the status with real-time progress from Tesseract
                    if (m.status === 'recognizing text') {
                        const progress = (m.progress * 100).toFixed(0);
                        updateStatus(`Detecting text... ${progress}%`);
                    } else {
                        updateStatus(m.status.charAt(0).toUpperCase() + m.status.slice(1) + '...');
                    }
                }
            }
        );

        // Display the detected text
        const detectedTitle = document.createElement('h3');
        detectedTitle.textContent = 'Detected Text:';
        detectedTitle.style.margin = '10px 0 5px 0';
        const detectedTextDiv = document.createElement('pre');
        detectedTextDiv.textContent = text.trim() || '(No text detected)';
        detectedTextDiv.style.whiteSpace = 'pre-wrap';
        detectedTextDiv.style.wordWrap = 'break-word';
        detectedTextDiv.style.padding = '10px';
        detectedTextDiv.style.backgroundColor = '#f0f0f0';
        detectedTextDiv.style.border = '1px solid #ddd';
        detectedTextDiv.style.borderRadius = '3px';
        detectedTextDiv.style.maxHeight = '200px';
        detectedTextDiv.style.overflowY = 'auto';


        container.appendChild(detectedTitle);
        container.appendChild(detectedTextDiv);

        if (!text.trim()) {
            updateStatus('Completed. No text was detected.');
            return container;
        }

        // 3. Translate the detected text using the MyMemory API
        updateStatus('Translating text...');

        // Map Tesseract's 3-letter language codes to ISO 639-1 (2-letter) codes for the API
        const langMap = {
            'eng': 'en', 'rus': 'ru', 'deu': 'de', 'fra': 'fr', 'spa': 'es', 'ita': 'it', 
            'por': 'pt', 'jpn': 'ja', 'chi_sim': 'zh-CN', 'chi_tra': 'zh-TW', 'kor': 'ko'
        };
        const sourceIso = langMap[sourceLang] || sourceLang;
        const targetIso = langMap[targetLang] || targetLang;

        const langPair = `${sourceIso}|${targetIso}`;
        const encodedText = encodeURIComponent(text);
        const apiUrl = `https://api.mymemory.translated.net/get?q=${encodedText}&langpair=${langPair}`;

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

        let translatedText = '(Translation not available)';
        if (translationData.responseStatus === 200) {
            translatedText = translationData.responseData.translatedText;
        } else {
            // Display the API's error message if available
            translatedText = `Error: ${translationData.responseDetails || 'Unknown translation error'}`;
        }

        updateStatus('Completed.');

        // 4. Display the translated text
        const translatedTitle = document.createElement('h3');
        translatedTitle.textContent = 'Translation:';
        translatedTitle.style.margin = '10px 0 5px 0';
        const translatedTextDiv = document.createElement('pre');
        translatedTextDiv.textContent = translatedText;
        translatedTextDiv.style.whiteSpace = 'pre-wrap';
        translatedTextDiv.style.wordWrap = 'break-word';
        translatedTextDiv.style.padding = '10px';
        translatedTextDiv.style.backgroundColor = '#e6f7ff';
        translatedTextDiv.style.border = '1px solid #cce5ff';
        translatedTextDiv.style.borderRadius = '3px';
        translatedTextDiv.style.maxHeight = '200px';
        translatedTextDiv.style.overflowY = 'auto';

        container.appendChild(translatedTitle);
        container.appendChild(translatedTextDiv);

        return container;

    } catch (error) {
        console.error('An error occurred during image processing:', error);
        updateStatus(`Error: ${error.message}`);
        return container;
    }
}

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 API Detector and Translator for Alphabet is an online tool that allows users to extract text from images using optical character recognition (OCR) and subsequently translate that text into another language. It utilizes Tesseract.js for text detection and the MyMemory API for translation. This tool is useful for anyone needing to convert printed or handwritten text from various languages into digital text, and for those looking to understand text that is not in their native language. Real-world use cases include translating signs, documents, and images containing text in various languages, making this tool beneficial for travelers, students, and professionals alike.

Leave a Reply

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