Please bookmark this page to avoid losing your image tool!

Image File 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.
/**
 * Translates text within an image using OCR and simulated translation.
 *
 * @param {Image} originalImg The original image object to process.
 * @param {string} targetLang The target language for translation (e.g., 'eng', 'rus', 'deu'). Note: This is for API compatibility; the actual translation is simulated.
 * @returns {Promise<HTMLCanvasElement>} A canvas element with the text replaced.
 */
async function processImage(originalImg, targetLang = 'eng') {

    // Helper function to dynamically load the Tesseract.js library from a CDN.
    // This ensures the library is available without needing to add it to the HTML.
    const loadTesseract = () => {
        return new Promise((resolve, reject) => {
            // If Tesseract is already loaded, resolve immediately.
            if (window.Tesseract) {
                return resolve();
            }
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';
            script.onload = () => resolve();
            script.onerror = (err) => reject(new Error(`Failed to load Tesseract.js: ${err}`));
            document.head.appendChild(script);
        });
    };

    try {
        await loadTesseract();
    } catch (error) {
        console.error(error);
        // Return a canvas with an error message if the library fails to load.
        const errorCanvas = document.createElement('canvas');
        errorCanvas.width = originalImg.naturalWidth;
        errorCanvas.height = originalImg.naturalHeight;
        const ctx = errorCanvas.getContext('2d');
        ctx.fillStyle = 'red';
        ctx.font = '16px sans-serif';
        ctx.fillText('Error: Could not load Tesseract.js library.', 10, 20);
        return errorCanvas;
    }


    // 1. Setup the canvas
    const canvas = document.createElement('canvas');
    canvas.width = originalImg.naturalWidth;
    canvas.height = originalImg.naturalHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(originalImg, 0, 0);

    // 2. Initialize Tesseract
    // We load both English and Russian to handle a wider range of source images.
    const worker = await Tesseract.createWorker('eng+rus', 1, {
       logger: m => console.log(m) // Optional: logs progress to the console
    });

    // 3. Perform OCR
    const { data: { lines } } = await worker.recognize(canvas);

    // 4. Process the recognized text: First, erase all identified text areas.
    // This prevents overlapping text boxes from interfering with each other.
    ctx.fillStyle = 'white'; // Use white to "erase" the text.
    ctx.strokeStyle = '#e0e0e0'; // Use a light border for visual debugging.
    ctx.lineWidth = 1;

    for (const line of lines) {
        // Only process text with a reasonable confidence score to avoid erasing non-text.
        if (line.confidence > 50) {
            const bbox = line.bbox;
            ctx.fillRect(bbox.x0, bbox.y0, bbox.width, bbox.height);
            ctx.strokeRect(bbox.x0, bbox.y0, bbox.width, bbox.height);
        }
    }

    // 5. "Translate" and draw placeholders
    // This loop runs after all areas have been erased.
    ctx.fillStyle = 'black';
    ctx.textAlign = 'left';
    ctx.textBaseline = 'top';

    for (const line of lines) {
        if (line.confidence > 50) {
            const bbox = line.bbox;
            const originalText = line.text;

            // --- SIMULATED TRANSLATION ---
            // In a real-world application with a server or API key, you would call a
            // translation service here:
            // const translatedText = await translateAPI(originalText, targetLang);
            //
            // For this client-side example, we create a placeholder of block characters
            // that has the same length as the original text.
            const placeholderText = '█'.repeat(originalText.replace(/\s/g, '').length);

            // Dynamically calculate font size to fit the placeholder text within the box.
            let fontSize = bbox.height;
            ctx.font = `${fontSize}px sans-serif`;
            let textWidth = ctx.measureText(placeholderText).width;

            // Reduce font size until the text fits within the bounding box width.
            while (textWidth > bbox.width && fontSize > 8) {
                fontSize -= 1;
                ctx.font = `${fontSize}px sans-serif`;
                textWidth = ctx.measureText(placeholderText).width;
            }
            
            // Vertically center the text within the bounding box.
            const y = bbox.y0 + (bbox.height - fontSize) / 2;
            ctx.fillText(placeholderText, bbox.x0, y);
        }
    }

    // 6. Clean up the Tesseract worker
    await worker.terminate();

    // 7. Return the final canvas
    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

Image File Translator is a tool that utilizes Optical Character Recognition (OCR) to identify and extract text from images. It allows users to upload an image and simulate the translation of the recognized text into a specified language, while also generating a visual representation of the image with the original text replaced by placeholders. This tool can be useful for users needing to translate signs, documents, or any text within images without having access to the original text content. Potential use cases include translating travel-related images, educational materials, or even assisting in language learning by converting text in pictures into simulated translations.

Leave a Reply

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