Please bookmark this page to avoid losing your image tool!

Image Title Translator For MS Paint Screenshot

(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 = 'eng', sourceLang = 'rus') {
    /**
     * Translates text found in an image, designed for screenshots like those from MS Paint.
     * It uses Tesseract.js for OCR and a free translation API.
     *
     * @param {Image} originalImg - The source Image object.
     * @param {string} targetLang - The 3-letter ISO 639-2 code for the target language (e.g., 'eng', 'fra', 'spa').
     * @param {string} sourceLang - The 3-letter ISO 639-2 code for the source language (e.g., 'rus', 'jpn', 'deu').
     * @returns {Promise<HTMLCanvasElement>} A canvas element with the text translated.
     */

    // Helper function to dynamically load a script
    const loadScript = (url) => {
        return new Promise((resolve, reject) => {
            // Check if script is already loaded
            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);
        });
    };
    
    // Helper function to decode HTML entities from the translation API response
    const decodeHtmlEntities = (text) => {
        const textarea = document.createElement('textarea');
        textarea.innerHTML = text;
        return textarea.value;
    };


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

    try {
        // Dynamically load Tesseract.js
        await loadScript('https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js');
    } catch (error) {
        console.error("Failed to load Tesseract.js:", error);
        // Return the original image on canvas if script fails
        return canvas;
    }

    // Perform OCR on the image
    const worker = await Tesseract.createWorker(sourceLang);
    const { data: { text, words } } = await worker.recognize(originalImg);
    await worker.terminate();

    // If no text is found, return the original image
    if (!text || words.length === 0) {
        console.warn("No text found in the image.");
        return canvas;
    }

    // Calculate a single bounding box for all recognized words
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    words.forEach(word => {
        const { x0, y0, x1, y1 } = word.bbox;
        minX = Math.min(minX, x0);
        minY = Math.min(minY, y0);
        maxX = Math.max(maxX, x1);
        maxY = Math.max(maxY, y1);
    });
    const bbox = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };

    // Translate the extracted text
    let translatedText = text.trim(); // Default to original text
    try {
        const q = encodeURIComponent(text.trim());
        const langpair = `${sourceLang}|${targetLang}`;
        const url = `https://api.mymemory.translated.net/get?q=${q}&langpair=${langpair}`;
        
        const response = await fetch(url);
        if (!response.ok) throw new Error(`API request failed with status ${response.status}`);
        
        const data = await response.json();
        if (data.responseData && data.responseData.translatedText) {
            translatedText = decodeHtmlEntities(data.responseData.translatedText);
        } else {
            console.warn("Translation API did not return translated text.", data);
        }
    } catch (error) {
        console.error("Translation failed:", error);
        // Fallback to original text is already handled as translatedText is pre-initialized
    }

    // Erase the original text by drawing a white rectangle over it
    // Add a small padding to ensure complete coverage
    const padding = 5;
    ctx.fillStyle = 'white'; // Assumes a white background, common in MS Paint
    ctx.fillRect(
        bbox.x - padding,
        bbox.y - padding,
        bbox.width + padding * 2,
        bbox.height + padding * 2
    );

    // Draw the new translated text onto the canvas
    ctx.fillStyle = 'black';
    ctx.textBaseline = 'middle';
    ctx.textAlign = 'center';
    
    // Dynamically adjust font size to fit within the original text's bounding box
    let fontSize = Math.ceil(bbox.height * 0.9); // Start with a font size based on box height
    let measuredWidth;

    do {
        ctx.font = `${fontSize}px Arial`;
        measuredWidth = ctx.measureText(translatedText).width;
        fontSize--;
    } while (measuredWidth > bbox.width && fontSize > 8);

    // Position the text in the center of the original bounding box
    const centerX = bbox.x + bbox.width / 2;
    const centerY = bbox.y + bbox.height / 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 Title Translator for MS Paint Screenshot is a tool designed to extract and translate text from images, particularly screenshots created in MS Paint. It utilizes OCR technology to read text from the image and a translation API to convert it into the desired language. This tool is especially useful for users who want to translate captions, labels, or any textual content present in their images, making it suitable for educational purposes, language learning, or sharing information across different languages. Users can specify the source and target languages for translation, enabling a wide range of multilingual applications.

Leave a Reply

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