Please bookmark this page to avoid losing your image tool!

Photo Text Analyzer 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', fontSize = 14, textColor = '#FF0000', backgroundColor = 'rgba(255, 255, 255, 0.8)') {

    /**
     * Dynamically loads a script from a URL and returns a promise that resolves when loaded.
     * @param {string} url The URL of the script to load.
     * @returns {Promise<void>}
     */
    const loadScript = (url) => {
        return new Promise((resolve, reject) => {
            // Check if the script is already on the page
            if (document.querySelector(`script[src="${url}"]`)) {
                return resolve();
            }
            const script = document.createElement('script');
            script.src = url;
            script.onload = () => resolve();
            script.onerror = () => reject(new Error(`Script load error for ${url}`));
            document.head.appendChild(script);
        });
    };

    /**
     * Translates a given text using a free, no-key translation API.
     * @param {string} text The text to translate.
     * @param {string} targetLang The target language code (e.g., 'en', 'es', 'fr').
     * @returns {Promise<string>} The translated text.
     */
    const translateText = async (text, targetLang) => {
        if (!text || !text.trim()) {
            return '';
        }
        // Using MyMemory API, which is free for anonymous use.
        // It auto-detects the source language if the language pair is specified like `|en`.
        const apiUrl = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=|${targetLang}`;
        try {
            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 API error: ${data.responseDetails}`);
            }
            return data.responseData.translatedText;
        } catch (error) {
            console.error('Translation failed:', error);
            // Return original text with an error marker in case of failure
            return `[Translation Error] ${text}`;
        }
    };
    
    /**
     * Draws word-wrapped text on a canvas context.
     * @param {CanvasRenderingContext2D} context The canvas 2D context.
     * @param {string} text The text to draw.
     * @param {number} x The starting X coordinate.
     * @param {number} y The starting Y coordinate.
     * @param {number} maxWidth The maximum width of a line.
     * @param {number} lineHeight The height of each line.
     */
    const wrapText = (context, text, x, y, maxWidth, lineHeight) => {
        const words = text.split(' ');
        let line = '';
        for (let n = 0; n < words.length; n++) {
            const testLine = line + words[n] + ' ';
            const metrics = context.measureText(testLine);
            const testWidth = metrics.width;
            if (testWidth > maxWidth && n > 0) {
                context.fillText(line, x, y);
                line = words[n] + ' ';
                y += lineHeight;
            } else {
                line = testLine;
            }
        }
        context.fillText(line, x, y);
    };

    // --- Main Function Logic ---

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = originalImg.naturalWidth;
    canvas.height = originalImg.naturalHeight;

    // Draw the original image first
    ctx.drawImage(originalImg, 0, 0);

    // Display a "processing" message over the image
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.fillRect(0, canvas.height / 2 - 30, canvas.width, 60);
    ctx.fillStyle = 'white';
    ctx.font = 'bold 24px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('Analyzing text, please wait...', canvas.width / 2, canvas.height / 2);

    try {
        // Step 1: Load the Tesseract.js library from a CDN
        await loadScript('https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js');

        // Step 2: Create a Tesseract worker to perform OCR
        // The logger is helpful for debugging progress in the browser console.
        const worker = await Tesseract.createWorker(sourceLang, 1, {
            logger: m => console.log(m)
        });
        
        // Step 3: Recognize text in the image
        const { data: { paragraphs } } = await worker.recognize(canvas);
        await worker.terminate();

        // Step 4: Redraw the original image to clear the "processing" message
        ctx.drawImage(originalImg, 0, 0);

        // Step 5: Process each found paragraph of text
        for (const p of paragraphs) {
            if (p.confidence < 50) continue; // Skip low-confidence detections

            const translatedText = await translateText(p.text, targetLang);
            const bbox = p.bbox;
            
            // Draw a background rectangle to cover the original text
            ctx.fillStyle = backgroundColor;
            ctx.fillRect(bbox.x0, bbox.y0, bbox.x1 - bbox.x0, bbox.y1 - bbox.y0);

            // Set text style for the translated text
            ctx.fillStyle = textColor;
            ctx.font = `${fontSize}px Arial`;
            ctx.textAlign = 'left';
            ctx.textBaseline = 'top';
            
            // Draw the translated text, wrapped to fit the original text's bounding box
            wrapText(ctx, translatedText, bbox.x0 + 2, bbox.y0 + 2, bbox.x1 - bbox.x0 - 4, fontSize * 1.2);
        }

    } catch (error) {
        console.error('An error occurred during image processing:', error);
        // Display an error message on the canvas if something goes wrong
        ctx.drawImage(originalImg, 0, 0); // Redraw image to clear previous state
        ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';
        ctx.fillRect(0, canvas.height / 2 - 30, canvas.width, 60);
        ctx.fillStyle = 'white';
        ctx.font = 'bold 18px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('Error during processing. See console for details.', canvas.width / 2, canvas.height / 2);
    }
    
    return canvas;
}

Free Image Tool Creator

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

Description

Photo Text Analyzer and Translator is an online tool that allows users to extract text from images and translate it into different languages. By utilizing Optical Character Recognition (OCR) technology, the tool can read text in various languages from uploaded images. Once the text is identified, users can specify a target language for translation. This tool is useful for translating documents, signs, or any text-based images, making it beneficial for travelers, students, and professionals who need quick and accessible translation solutions.

Leave a Reply

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