Please bookmark this page to avoid losing your image tool!

Image Text Annotation 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, textToTranslate = 'Hello World', targetLang = 'es', sourceLang = 'en', positionX = 50, positionY = 50, fontSize = 48, fontColor = '#FFFFFF', fontFamily = 'Roboto', textAlign = 'left', backgroundColor = 'rgba(0, 0, 0, 0.5)') {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // Ensure the image is fully loaded before drawing to the canvas
    if (!originalImg.complete || originalImg.naturalWidth === 0) {
        await new Promise((resolve, reject) => {
            originalImg.onload = resolve;
            originalImg.onerror = reject;
        });
    }

    canvas.width = originalImg.naturalWidth;
    canvas.height = originalImg.naturalHeight;

    // Dynamically load the specified font from Google Fonts if it's not a standard web-safe font.
    // This allows for a wide variety of font choices.
    try {
        const webSafeFonts = ["serif", "sans-serif", "monospace", "cursive", "fantasy", "Arial", "Verdana", "Times New Roman", "Courier New", "Georgia"];
        const isWebSafe = webSafeFonts.some(font => fontFamily.toLowerCase().includes(font.toLowerCase()));

        if (!isWebSafe) {
            const fontName = fontFamily.replace(/ /g, '+');
            const fontUrl = `https://fonts.googleapis.com/css2?family=${fontName}:wght@400;700&display=swap`;

            // Add the font stylesheet to the document head if it's not already there.
            if (!document.querySelector(`link[href="${fontUrl}"]`)) {
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = fontUrl;
                document.head.appendChild(link);
                // Wait for the font to be loaded and ready for use.
                await document.fonts.load(`1em "${fontFamily}"`);
            }
        }
    } catch (error) {
        console.error(`Font loading failed for '${fontFamily}', falling back to Arial.`, error);
        fontFamily = 'Arial'; // Fallback to a safe font in case of an error.
    }

    // Translate the text using the free MyMemory Translated API.
    let translatedText = textToTranslate; // Default to the original text if translation fails.
    try {
        const langPair = `${sourceLang}|${targetLang}`;
        const apiUrl = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(textToTranslate)}&langpair=${langPair}`;
        const response = await fetch(apiUrl);
        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 = data.responseData.translatedText;
        } else {
            console.warn('Translation could not be retrieved from API response:', data);
        }
    } catch (error) {
        console.error('Translation failed:', error);
    }

    // Draw the original image onto the canvas.
    ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);

    // Prepare text rendering settings.
    ctx.font = `${fontSize}px "${fontFamily}"`;
    ctx.textAlign = textAlign;
    ctx.textBaseline = 'top';

    // Draw a semi-transparent background for the text to ensure readability.
    if (backgroundColor && backgroundColor !== 'transparent') {
        const padding = fontSize * 0.2;
        const textMetrics = ctx.measureText(translatedText);
        const textWidth = textMetrics.width;
        // Using fontSize for height is a reliable cross-browser way to estimate text block height.
        const textHeight = fontSize;

        let rectX;
        const rectY = positionY - padding;
        const rectWidth = textWidth + (padding * 2);
        const rectHeight = textHeight + (padding * 2);

        // Adjust the background rectangle's position based on the text alignment.
        if (textAlign === 'center') {
            rectX = positionX - (textWidth / 2) - padding;
        } else if (textAlign === 'right') {
            rectX = positionX - textWidth - padding;
        } else { // Default to 'left'
            rectX = positionX - padding;
        }

        ctx.fillStyle = backgroundColor;
        ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
    }

    // Draw the final translated text onto the canvas.
    ctx.fillStyle = fontColor;
    ctx.fillText(translatedText, positionX, positionY);

    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 Annotation Translator is a web-based tool that allows users to add translated text annotations to images. By simply uploading an image, users can specify text to be translated, select the source and target languages, and position the text on the image. This tool is useful for creating personalized images for social media, educational materials, or any purpose where bilingual or multilingual captions are needed. Users can customize the font, size, color, and background of the text to enhance readability and aesthetics, making it suitable for various creative projects.

Leave a Reply

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