Please bookmark this page to avoid losing your image tool!

Image Text 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, targetLang = "ru", sourceLang = "eng") {
    // Create a canvas to process and output the new image
    const canvas = document.createElement('canvas');
    canvas.width = originalImg.width || originalImg.naturalWidth;
    canvas.height = originalImg.height || originalImg.naturalHeight;
    const ctx = canvas.getContext('2d');
    
    // Draw the original image onto the canvas
    ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);

    // Dynamically load Tesseract.js (Optical Character Recognition library)
    if (typeof window.Tesseract === 'undefined') {
        await new Promise((resolve, reject) => {
            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;
            document.head.appendChild(script);
        });
    }

    let result;
    try {
        // Initialize Tesseract worker and recognize text
        const worker = await window.Tesseract.createWorker(sourceLang);
        result = await worker.recognize(canvas);
        await worker.terminate();
    } catch (error) {
        console.error("OCR Error:", error);
        return canvas; // Exiting with original image if OCR fails
    }

    const lines = result.data.lines;

    // Process translation and overlay line by line
    for (const line of lines) {
        const text = line.text.trim();
        if (!text) continue;

        let translatedText = text;
        
        // Fetch translation using the unofficial Google Translate API endpoint 
        try {
            const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}`;
            const res = await fetch(url);
            if (res.ok) {
                const json = await res.json();
                // Reconstruct the translated string from the result array
                translatedText = json[0].map(item => item[0]).join('');
            }
        } catch (error) {
            console.error("Translation Error (possibly rate-limited):", error);
        }

        // Get original bounding box data
        const { x0, y0, x1, y1 } = line.bbox;
        const pad = 3; // Padding for the bounding box
        
        const x = Math.max(0, x0 - pad);
        const y = Math.max(0, y0 - pad);
        let w = (x1 - x0) + pad * 2;
        let h = (y1 - y0) + pad * 2;

        // Clamp bounding box to prevent stretching outside the canvas
        w = Math.min(canvas.width - x, w);
        h = Math.min(canvas.height - y, h);

        // Calculate an approximate background color of the region
        let bgR = 255, bgG = 255, bgB = 255;
        try {
            // Sample pixels right outside the top-left and bottom-right corners
            const tl = ctx.getImageData(Math.max(0, x - 1), Math.max(0, y - 1), 1, 1).data;
            const br = ctx.getImageData(Math.min(canvas.width - 1, x + w + 1), Math.min(canvas.height - 1, y + h + 1), 1, 1).data;
            bgR = Math.round((tl[0] + br[0]) / 2);
            bgG = Math.round((tl[1] + br[1]) / 2);
            bgB = Math.round((tl[2] + br[2]) / 2);
        } catch (e) {
            // Silently fallback to white on CORS canvas errors
        }

        // Overwrite the original text with a solid background box
        ctx.fillStyle = `rgb(${bgR}, ${bgG}, ${bgB})`;
        ctx.fillRect(x, y, w, h);

        // Determine a text color with appropriate contrast based on brightness
        const brightness = (bgR * 299 + bgG * 587 + bgB * 114) / 1000;
        ctx.fillStyle = brightness > 125 ? '#000000' : '#ffffff';

        // Set up the font and baseline
        let fontSize = h * 0.7; // Start point for font size dependent on bounding box height
        ctx.textBaseline = 'middle';
        ctx.textAlign = 'center';
        ctx.font = `${fontSize}px sans-serif`;

        // Scale down the font if the translation string is too long for the bounding box width
        let metrics = ctx.measureText(translatedText);
        if (metrics.width > w * 0.95) {
            fontSize = fontSize * ((w * 0.95) / metrics.width);
            ctx.font = `${fontSize}px sans-serif`;
        }

        // Draw the translated text directly in the center of the original box
        const centerX = x + w / 2;
        const centerY = y + h / 2;
        ctx.fillText(translatedText, centerX, centerY);
    }

    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

The Image Text Translator is a tool designed to detect, remove, and replace text within an image with translated content. Using optical character recognition (OCR), the tool identifies text in an uploaded image, translates it into a target language, and overlays the new text back onto the image while attempting to match the original background color. This tool is useful for translating foreign language signs, menus, documents, or infographics, allowing users to understand visual content in different languages without losing the original context.

Leave a Reply

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