Please bookmark this page to avoid losing your image tool!

Photo 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.
/**
 * Detects text in an image using OCR and overlays interactive links that
 * open Google Translate to translate the detected text.
 * This function handles dynamic loading of the Tesseract.js library.
 *
 * @param {HTMLImageElement} originalImg The original image to process.
 * @param {string} [targetLang='en'] The 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 source image (e.g., 'eng', 'spa', 'fra').
 * @returns {Promise<HTMLElement>} A promise that resolves to a single div element containing the image and interactive translation overlays.
 */
async function processImage(originalImg, targetLang = 'en', ocrLang = 'eng') {
    // This is the main container element that will be returned.
    // It's styled to precisely wrap the canvas and position overlays on top of it.
    const wrapper = document.createElement('div');
    wrapper.style.position = 'relative';
    wrapper.style.display = 'inline-block';
    wrapper.style.fontFamily = 'Arial, sans-serif';

    // A canvas is used to display the original image.
    const canvas = document.createElement('canvas');
    canvas.width = originalImg.naturalWidth;
    canvas.height = originalImg.naturalHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(originalImg, 0, 0);
    wrapper.appendChild(canvas);

    // A status display provides feedback to the user during the OCR process, which can be slow.
    const statusDisplay = document.createElement('div');
    statusDisplay.style.position = 'absolute';
    statusDisplay.style.inset = '0'; // Covers the entire wrapper (top, right, bottom, left = 0)
    statusDisplay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    statusDisplay.style.color = 'white';
    statusDisplay.style.display = 'flex';
    statusDisplay.style.justifyContent = 'center';
    statusDisplay.style.alignItems = 'center';
    statusDisplay.style.textAlign = 'center';
    statusDisplay.style.fontSize = '1.2em';
    statusDisplay.innerText = 'Initializing...';
    wrapper.appendChild(statusDisplay);

    // Helper function to dynamically load the Tesseract.js library from a CDN.
    // It ensures the script is loaded only once.
    const loadTesseractScript = () => {
        return new Promise((resolve, reject) => {
            if (window.Tesseract) {
                return resolve(); // Already loaded
            }
            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(new Error('Failed to load Tesseract.js OCR library.'));
            document.head.appendChild(script);
        });
    };

    try {
        await loadTesseractScript();
        statusDisplay.innerText = 'Loading OCR model...';

        // Create a Tesseract worker. The logger provides progress updates.
        const worker = await Tesseract.createWorker(ocrLang, 1, {
            logger: m => {
                if (m.status === 'recognizing text') {
                    const progress = (m.progress * 100).toFixed(0);
                    statusDisplay.innerText = `Recognizing Text: ${progress}%`;
                } else {
                    const statusText = m.status.charAt(0).toUpperCase() + m.status.slice(1);
                    statusDisplay.innerText = `${statusText}...`;
                }
            },
        });

        // Perform OCR on the image canvas.
        const {
            data: {
                paragraphs
            }
        } = await worker.recognize(canvas);

        // Remove the progress display overlay.
        wrapper.removeChild(statusDisplay);

        // Iterate through the detected paragraphs to create interactive links.
        paragraphs.forEach(p => {
            const {
                bbox,
                text
            } = p;
            
            // Ignore paragraphs with no actual text content.
            if (!text || !text.trim()) return;

            const link = document.createElement('a');
            link.style.position = 'absolute';
            link.style.left = `${bbox.x0}px`;
            link.style.top = `${bbox.y0}px`;
            link.style.width = `${bbox.x1 - bbox.x0}px`;
            link.style.height = `${bbox.y1 - bbox.y0}px`;
            link.style.backgroundColor = 'rgba(255, 255, 0, 0.2)'; // Yellow highlight
            link.style.border = '2px solid yellow';
            link.style.cursor = 'pointer';
            link.style.boxSizing = 'border-box';

            // Construct the Google Translate URL.
            const encodedText = encodeURIComponent(text.trim());
            const translateUrl = `https://translate.google.com/?sl=auto&tl=${targetLang}&text=${encodedText}&op=translate`;
            link.href = translateUrl;
            link.target = '_blank'; // Open in a new tab
            link.title = `Click to translate: "${text.trim().substring(0, 80)}..."`;

            wrapper.appendChild(link);
        });

        // Terminate the worker to free up browser resources.
        await worker.terminate();

    } catch (error) {
        console.error('Photo Translator Error:', error);
        statusDisplay.style.backgroundColor = 'rgba(200, 0, 0, 0.8)';
        statusDisplay.innerText = `Error: ${error.message}`;
    }

    return wrapper;
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

Photo Translator is an online tool that uses Optical Character Recognition (OCR) to detect text in images and overlays interactive links that allow users to translate the detected text using Google Translate. This tool can be particularly useful for travelers who encounter foreign signs or menus, students studying foreign languages, or anyone needing to translate printed materials. By providing instant translation access directly from images, it enhances accessibility and understanding of foreign languages in visual contexts.

Leave a Reply

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